Observer Pattern in Python

Level 5534 keystrokes

This implements the Observer pattern. Subject notifies all attached observers when its state changes.

Python code

# Subject is the class being observed
# Maintains list of observers and notifies them of changes
1class Subject:
# __init__ sets up observer list and initial state
2 def __init__(self):
# List to hold observer references
3 self._observers: list = []
# State that observers are interested in
4 self._state: int = 0
5
# attach adds an observer to be notified
# observer must have update() method
6 def attach(self, observer):
# Add observer to the list
7 self._observers.append(observer)
8
# set_state changes state and notifies observers
# state is the new value to set
9 def set_state(self, state: int):
# Update internal state
10 self._state = state
# Notify all observers of the change
11 self._notify()
12
# _notify is internal by convention (leading underscore)
# Called automatically when state changes
13 def _notify(self):
# Loop through all registered observers
14 for observer in self._observers:
# Call each observer's update with new state
15 observer.update(self._state)
16
# Observer receives notifications from Subject
# Each observer has a name for identification
17class Observer:
# __init__ takes name to identify this observer
18 def __init__(self, name: str):
19 self.name = name
20
# update is called by Subject when state changes
# state is the new state value
21 def update(self, state: int):
# Print notification with observer name and new state
22 print(f"{self.name} received: {state}")
23
# Create Subject to be observed
24subject = Subject()
# Attach Observer named "A"
25subject.attach(Observer("A"))
# Attach Observer named "B"
26subject.attach(Observer("B"))
# Set state to 42, triggering notifications
# Both A and B will receive the update
27subject.set_state(42)

Output

A received: 42
B received: 42
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • _× 18
  • (× 16
  • )× 16
  • :× 15
  • .× 14
  • "× 6
  • =× 5
  • ,× 4
  • {× 2
  • }× 2

More Python examples at level 5

← Python typing practice