Python Design Patterns

Observer Pattern in Python

Notify every subscriber automatically when something changes, like email and SMS alerts when an order ships.

  • Advanced
  • 2 min read
  • 1 runnable example
What you'll learn
  • Subjects and observers
  • subscribe and notify
  • Loose coupling between publisher and subscribers
order.set_status("shipped")
  • Ordersubject
    • email listenerEmail received: shipped
    • any 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.

From a newsletter to code
order.subscribe(...)📝 A reader signs up
self.listeners📋 The mailing list
order.set_status("shipped")📰 A new issue is published
listener(status)📬 Every subscriber receives it
Publish once; every subscriber reacts in its own way.
In one sentence

The Observer pattern lets objects subscribe to another object (the subject) and be notified automatically whenever it changes.

Key points

  1. self.listeners is the list of subscribers.
  2. subscribe(listener) adds a function to that list.
  3. set_status(status) calls every listener with the new status.
  4. Order does 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

Run 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")
Get a Run button for this example

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.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in the Python compiler →

Common mistakes

Calling the listeners directly from the subject

Each new reaction then requires editing the Order class.

Problem
def set_status(self, status):
    send_email(status)
    update_dashboard(status)
Fix
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