How to implement the observer pattern in Python
· Category: Python Programming
Short answer
The observer pattern lets one object (the subject) notify multiple dependents (observers) automatically when its state changes. In Python, you can implement it with callback lists, the built-in weakref module, or third-party pub/sub libraries.
Details
A minimal implementation stores a list of observer callables and invokes them on state changes:
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def notify(self, data):
for observer in self._observers:
observer(data)
For production systems, use weakref.WeakMethod to avoid preventing garbage collection. The observer pattern aligns naturally with Python classes and objects when subjects encapsulate state and observers encapsulate reactions. You can also use Python decorators to auto-register observer methods, or leverage Python generators to yield events to consumers lazily. Libraries like PyPubSub offer thread-safe topic-based messaging if you need broader decoupling.
Tips
- Always remove observers or use weak references to prevent memory leaks.
- Keep observer callbacks fast; offload heavy work to background tasks.
- Use typed protocols if you combine this pattern with Python type hints for better IDE support.