Observer
Observer is a publish/subscribe split: a subject keeps a list of callables and notifies them when its state changes. Listeners do not poll; they are called.
Detailed Explanation
A button does not know about analytics, logging, and a stock update. It holds subscribers and, on click, calls each one. That is observer. In Python the subscribers are usually functions or bound methods, not a formal Observer interface. subject.subscribe(fn) / subject.notify(event) is the whole object.
The subject must not assume a subscriber succeeds. One raising listener should not prevent the others from running unless you want fail-fast. Collect errors or log and continue. Document which it is.
Lifetime is the hard part. button.subscribe(order.on_paid) stores a bound method and keeps order alive. A short-lived order subscribed to a long-lived event bus is a leak. Use weakref.WeakMethod, an explicit unsubscribe, or subscribe a function that does not close over the whole object.
Synchronous notify is simpler and re-entrant: a listener that mutates the subject can notify again and overflow the stack. Either forbid that or queue notifications. Async buses (asyncio) notify by creating tasks; then ordering is no longer "listeners ran in list order before notify returned".
The standard library has pieces: logging handlers, pathlib watchers in third-party packages, blinker and pyee if you want a library. Django signals are observers. Do not build a global signal mesh for a feature that is one function call.
When there is one listener, just call it. Observer pays for itself at two and above, or when the set of listeners is configured at runtime.
Code Examples
class Bus:
def __init__(self) -> None:
self._subs: list = []
def subscribe(self, fn) -> None:
self._subs.append(fn)
def notify(self, event: str) -> None:
for fn in list(self._subs):
fn(event)
bus = Bus()
seen: list[str] = []
bus.subscribe(seen.append)
bus.notify("paid")
print(seen) # ['paid']# Unsubscribe so a long-lived bus does not pin the listener.
def subscribe_once(bus: Bus, fn) -> None:
def wrapper(event: str) -> None:
bus._subs.remove(wrapper)
fn(event)
bus.subscribe(wrapper)Common Gotchas
Iterating `self._subs` while a listener unsubscribes
skip or crash. Iterate a copy.
Bound methods keep the instance
unsubscribe in `close()`, or use a weak reference.
A listener that calls `notify`
re-entrancy. Queue events if that is allowed.
One callback is a parameter, not a bus
do not add infrastructure for a single hook.