Mediator Pattern Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Mediator Pattern runs in O(n) time and O(n) space, in Python as in every other language.
- ✓There is no event bus in the standard library. The pieces you build one from are a dictionary of event name to a list of handlers, weakref and weakref.WeakMethod for subscriptions that do not own their subscribers, and asyncio for the asynchronous case where asyncio.Queue is the hub and asyncio.gather fans out.
- ✓Store handlers with weakref.WeakMethod when they are bound methods and weakref.ref when they are functions, so unsubscribing is not mandatory for correctness; a reviewer will ask what happens when a subscriber is garbage collected without unsubscribing.
- ✓The Python trap: A plain list of bound methods keeps every subscriber alive forever, because a bound method holds a strong reference to its instance, so a long-lived hub silently pins every object that ever subscribed and the leak grows with uptime rather than with load.
- ✓Dispatch is a dictionary lookup plus one Python call per subscriber, so the cost is linear in subscriber count and dominated by call overhead rather than by the lookup.
What Mediator Pattern actually is
Mediator Pattern in Python: what you actually reach for
Python implementation
import weakref
from collections import defaultdict
from typing import Callable
class Mediator:
def __init__(self) -> None:
self._subs: dict[str, list] = defaultdict(list)
def subscribe(self, event: str, handler: Callable) -> Callable[[], None]:
# WeakMethod for bound methods: the hub must not OWN its subscribers.
ref = weakref.WeakMethod(handler) if hasattr(handler, "__self__") else weakref.ref(handler)
self._subs[event].append(ref)
return lambda: self._subs[event].remove(ref)
def publish(self, event: str, payload: object) -> None:
dead = []
for ref in list(self._subs[event]): # copy: we prune while iterating
fn = ref()
if fn is None:
dead.append(ref) # collected: prune afterwards
continue
fn(payload)
for d in dead:
self._subs[event].remove(d)
class Widget:
def on_save(self, payload): print("saved", payload)
hub = Mediator()
w = Widget()
hub.subscribe("save", w.on_save)
hub.publish("save", {"id": 1})
del w
hub.publish("save", {"id": 2}) # no handler: the weak ref pruned itselfThink Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Mediator Pattern?
There is no event bus in the standard library. The pieces you build one from are a dictionary of event name to a list of handlers, weakref and weakref.WeakMethod for subscriptions that do not own their subscribers, and asyncio for the asynchronous case where asyncio.Queue is the hub and asyncio.gather fans out. For in-process signals most projects reach for blinker, which Flask uses, and it stores receivers weakly by default for exactly the reason below.
What is the most common Python mistake when implementing Mediator Pattern?
A plain list of bound methods keeps every subscriber alive forever, because a bound method holds a strong reference to its instance, so a long-lived hub silently pins every object that ever subscribed and the leak grows with uptime rather than with load. WeakMethod fixes it but introduces the dead-entry problem: the reference yields None after collection and the hub must prune, which cannot be done while iterating the same list. Iterate over a copy and prune afterwards.
How does Mediator Pattern actually perform in Python?
Dispatch is a dictionary lookup plus one Python call per subscriber, so the cost is linear in subscriber count and dominated by call overhead rather than by the lookup. Dereferencing a weak reference is cheap but not free and adds a check per handler per event. For high-frequency events the usual optimisation is to resolve the handler list once into a local tuple and iterate that, avoiding repeated attribute lookups on the hub. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.