Observer Pattern in Python
Observer decouples the publisher of an event from any number of interested subscribers.
What is Observer Pattern?
Observer decouples the publisher of an event from any number of interested subscribers.
Notify subscribed objects automatically when subject state changes.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example code
main.py
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")
Expected output
Email received: shipped
How it works
Order publishes its new status to every subscribed function without knowing their implementation.
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.