Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Mediator Pattern Implementation in Python

19 min readadvanced
Website QA and SEO audits

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

A mediator replaces many-to-many wiring between components with a hub: colleagues publish to it and subscribe from it, and they never hold references to one another. The pattern trades direct coupling for indirection, and the price of that trade is paid in two currencies that differ enormously across these eight languages. The first is lifetime: a hub holding a strong reference to every subscriber keeps them all alive, which is the single most common memory leak in event-driven code, and each runtime offers a different escape. The second is failure: when a subscriber throws, does the publisher find out? Two platforms here silently swallow it, one crashes the whole process by default, and one makes the question moot because the hub is a language primitive that carries values rather than invoking callbacks.

Mediator Pattern in Python: what you actually reach for

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.

Python implementation

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. Return an unsubscribe callable from subscribe so callers have a token rather than having to reconstruct the handler identity. Decide explicitly whether one failing handler stops the fan-out, and document it.
python
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 itself

Think 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 Free

The Python-specific 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. 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.

Performance in Python, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Mediator Pattern between languages.

Real-World Applications

Mediator Pattern is used extensively in production software: framework internals, plugin architectures, state management libraries, and large-scale application architectures all rely on this pattern. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Mediator Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Mediator Pattern appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Mediator Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Mediator Pattern to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Replit free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.