Observer Pattern in Python
Notify every subscriber automatically when something changes, like email and SMS alerts when an order ships.
- Subjects and observers
- subscribe and notify
- Loose coupling between publisher and subscribers
Ordersubjectemail listenerEmail received: shippedany other listenergets "shipped" too
Publish once, every subscriber reacts
The problem
When an order ships, many parts of a system may need to react: send an email, update the dashboard, notify the warehouse. If the order class calls each of them directly, it must change every time a new reaction is added.
Think of it like this
The Observer pattern is like subscribing to a newsletter. Readers sign up once, and every time a new issue comes out, the publisher sends it to everyone on the list. The publisher does not need to know what each reader does with it.
order.subscribe(...)📝 A reader signs upself.listeners📋 The mailing listorder.set_status("shipped")📰 A new issue is publishedlistener(status)📬 Every subscriber receives itThe Observer pattern lets objects subscribe to another object (the subject) and be notified automatically whenever it changes.
Key points
self.listenersis the list of subscribers.subscribe(listener)adds a function to that list.set_status(status)calls every listener with the new status.Orderdoes not know what the listeners do; here one prints an email message.
When should you use it?
- Events in user interfaces: clicks, input changes.
- Notifications when data changes: emails, dashboards, caches.
- Decoupling the code that causes an event from the code that reacts to it.
When not to use it
- Only one fixed reaction exists: calling it directly is clearer.
- Many chained observers triggering each other: the flow becomes hard to follow and debug.
Example code
class Order:
# Observer: publish changes to an open-ended subscriber list.
def __init__(self): self.listeners = []
def subscribe(self, listener): self.listeners.append(listener)
def set_status(self, status):
# Broadcast the change to all current observers.
for listener in self.listeners:
listener(status)
order = Order()
order.subscribe(lambda status: print(f"Email received: {status}"))
order.set_status("shipped")
Result of running the code
Email received: shipped
Code explanation
Order keeps a list of listener functions. subscribe adds the lambda that prints an email message, and set_status("shipped") loops over the list and calls each listener with the new status. Order never needs to know what its listeners do, so new reactions can be added just by subscribing them.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Common mistakes
Calling the listeners directly from the subject
Each new reaction then requires editing the Order class.
def set_status(self, status):
send_email(status)
update_dashboard(status)
def set_status(self, status):
for listener in self.listeners:
listener(status)
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges