The Observer Pattern in Python: Notifying Subscribers Automatically
This article explains how the Observer pattern lets an object notify any number of subscribers in Python, using callables, properties and weak references, and how to handle observers removed during a notification, lapsed listeners and failing callbacks.
When the state of one object changes, other parts of a program often need to react: a display must redraw a new temperature, a cache must be invalidated, a log must record the event. If the object that changes calls each of those parts by name, it must know all of them, and every new reaction requires editing it. The present article addresses the Observer pattern, which inverts that dependency: the object keeps a list of subscribers that it does not know in detail and notifies them all when its state changes. It shows the idiomatic form of the pattern in Python, based on callables rather than on a hierarchy of classes, and examines the errors that appear in real implementations: observers removed during a notification, observers kept alive by the subject and observers that fail. A subject that knows nothing about its listeners is the secret weapon of this pattern.
Subjects, Observers and Subscriptions
The Observer pattern, described in 1994 in the classic catalogue of design patterns and also known as event-subscriber or listener, defines a one-to-many dependency: one subject, many observers, and an automatic notification from the first to the second. The classic formulation gives the subject three operations, to attach an observer, to detach it and to notify all of them, and requires every observer to implement a method such as update. In Python, functions and bound methods are objects that can be stored and called, so the subject can simply keep a list of callables, and any function can subscribe without inheriting from a common class.
class WeatherStation:
def __init__(self):
self._temperature = None
self._subscribers = []
def subscribe(self, callback):
self._subscribers.append(callback)
return callback
def unsubscribe(self, callback):
self._subscribers.remove(callback)
@property
def temperature(self):
return self._temperature
@temperature.setter
def temperature(self, value):
if value == self._temperature:
return
self._temperature = value
for callback in tuple(self._subscribers):
callback(value)
station = WeatherStation()
@station.subscribe
def phone(value):
print(f"phone: {value} C")
class Dashboard:
def __init__(self):
self.history = []
def update(self, value):
self.history.append(value)
dashboard = Dashboard()
station.subscribe(dashboard.update)
station.temperature = 25 # Output: phone: 25 C
station.temperature = 25 # no change, no notification
station.temperature = 10 # Output: phone: 10 C
print(dashboard.history) # Output: [25, 10]
The station knows neither phone nor Dashboard; it only calls whatever was subscribed. The property setter notifies only when the value really changes, so the repeated assignment of 25 produces no message. Because subscribe returns the callback it receives, it can also be applied as a decorator, the construction examined in the article devoted to decorators. This example follows the push model, in which the subject sends the new value; in the pull model of the classic formulation, the subject sends itself and each observer reads what it needs, which is useful when observers require different parts of a large state.
Between notifications, an observer does nothing at all. In the words of a certain armoured soldier before cryosleep, "wake me when you need me": the observer neither asks for the temperature nor checks it periodically, and it runs only when the subject calls it. This is the difference between observing and polling, in which every interested object would have to ask repeatedly whether something has changed.
Removing Observers During a Notification
An observer may need to unsubscribe while it is being notified, for example a callback that reacts only to the first event. If the subject iterates directly over its list, the removal shifts the remaining elements and the loop skips one of them.
received = []
def make(name, observers, once=False):
def callback(value):
received.append(name)
if once:
observers.remove(callback)
return callback
observers = []
observers += [make("a", observers, once=True), make("b", observers), make("c", observers)]
for callback in observers:
callback(1)
print(received) # Output: ['a', 'c']
received.clear()
observers = []
observers += [make("a", observers, once=True), make("b", observers), make("c", observers)]
for callback in tuple(observers):
callback(1)
print(received) # Output: ['a', 'b', 'c']
In the first loop, the removal of a moves b to the position that the iteration has already passed, so b is never notified and no error reveals the omission. Iterating over a copy, tuple(observers), makes the notification independent of changes to the list, which is why the station of the previous example uses it.
Observers That Outlive Their Use
A list of callbacks holds strong references, so every subscribed object stays alive for as long as the subject exists, even after the rest of the program has forgotten it. This leak is known as the lapsed listener problem, and its usual remedy is to keep weak references, the mechanism described in the article devoted to weak references.
import gc
import weakref
class Display:
def __init__(self, log):
self.log = log
def update(self, value):
self.log.append(value)
def notify(refs, value):
for ref in refs:
method = ref()
if method is not None:
method(value)
log = []
strong = []
display = Display(log)
strong.append(display.update)
del display
gc.collect()
for callback in strong:
callback(1)
print(log) # Output: [1]
weak = weakref.WeakSet()
display = Display(log)
weak.add(display.update)
print(len(weak)) # Output: 0
refs = [weakref.WeakMethod(display.update)]
notify(refs, 2)
del display
gc.collect()
notify(refs, 3)
print(log, refs[0]() is None) # Output: [1, 2] True
The deleted display still received the value 1, because the bound method in the list keeps its instance alive. A WeakSet does not solve the problem for methods: each access to display.update creates a new bound method that nobody else references, so the set loses it at once. weakref.WeakMethod, available since Python 3.4, references the instance and the function separately, delivers the value 2 while the display exists and returns None after it has been collected, so the value 3 reaches nobody.
Pitfalls of the Observer Pattern
The pattern removes explicit dependencies, but it also makes the flow of a program harder to follow, since a single assignment can run code located anywhere. Six pitfalls are distinguished, which are the following:
- Modifying the list during a notification. Iterating directly over the subscribers skips observers when one of them unsubscribes; a copy must be iterated.
- Lapsed listeners. Strong references keep forgotten observers alive and notified; observers must unsubscribe explicitly or be held through
WeakMethod. - One failure stops everyone. An exception raised by one observer interrupts the loop, and the remaining observers are never notified.
- Order dependence. Observers that rely on being called in a particular order create hidden coupling; the pattern does not guarantee an order in general.
- Cascades and recursion. An observer that modifies the subject triggers a new notification inside the current one, which may loop indefinitely.
- Coupling through type checks. Observers that test
isinstance(subject, WeatherStation), as many textbook examples do, are bound again to the concrete subject that the pattern intended to hide.
The third pitfall is solved by calling each observer inside its own try block and reporting the errors afterwards, as the following example shows.
def broken(value):
raise ValueError("display offline")
def logger(value):
print("logged", value)
subscribers = [broken, logger]
errors = []
for callback in tuple(subscribers):
try:
callback(30)
except Exception as error:
errors.append((callback.__name__, error))
# Output: logged 30
print(errors) # Output: [('broken', ValueError('display offline'))]
The failing observer no longer prevents the logger from receiving the value, and the collected errors can be logged or raised together once every observer has been called. When observers run in other threads, the list of subscribers must also be protected by a lock, or the notifications must be passed through a thread-safe queue.
Choosing a Notification Mechanism
Consequently, the right mechanism depends on how many parties take part and on how long they live, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| One object must call exactly one function when something happens | A plain callback argument |
| One subject, several independent observers | A list of callables with subscribe and unsubscribe |
| Observers whose lifetime the subject must not extend | weakref.WeakMethod or explicit unsubscription |
| Observers that may fail | Guard each call and report the errors afterwards |
| Notifications that cross threads | A lock around the subscribers or a thread-safe queue |
| Many objects that notify one another | A central mediator instead of a web of subscriptions |
Conclusion
It is concluded that the Observer pattern lets an object announce its changes to any number of subscribers without knowing them, and that Python reduces it to a list of callables, a subscription method and a notification loop over a copy of that list. This magic requires care with lifetimes, failures and the order of calls, which the weak references of the standard library and a guarded loop resolve. When many objects begin to observe one another, the subscriptions form a web that is hard to follow, and the Mediator pattern, which centralizes that communication in a single object, is developed in a future article of this series.