CodeBlanks Logo Icon CodeBlanks

Observer

Learn the Observer pattern.

Observer

The Observer pattern lets an object notify its subscribers about state changes. The Subject keeps subscribers in a list; when notify is called, each gets the message.

class Subject:
    def __init__(self):
        self._observers = []
    def subscribe(self, obs):
        self._observers.append(obs)
    def notify(self, value):
        for obs in self._observers:
            obs(value)

Subscribers are callable; this is common in event-driven interfaces and messaging systems.

Subscribing and notifying

To add a subscriber, call subscribe(obs); obs is callable (a function or an object with a __call__ method). Notification is done with notify(value).

def log_observer(value):
    print(f"log: {value}")

s = Subject()
s.subscribe(log_observer)
s.notify("merhaba")  # log: merhaba

Multiple subscribers can be added; all get the same value. This is good for logging, cache invalidation and UI updates.

Practice Log with Observer

Define class Subject:. In __init__ set self._observers = []. Method def subscribe(self, obs): does self._observers.append(obs). Method def notify(self, value): does for obs in self._observers: obs(value). Function def log_observer(value): does print(f"log: {value}"). Create s = Subject(), call s.subscribe(log_observer) and s.notify("merhaba").

Starter code

main.py
# define Subject class (observers list, subscribe and notify)
# define log_observer function (prints value)
# create a Subject, subscribe log_observer and call notify

Sample solution

main.py
class Subject:
    def __init__(self):
        self._observers = []
    def subscribe(self, obs):
        self._observers.append(obs)
    def notify(self, value):
        for obs in self._observers:
            obs(value)

def log_observer(value):
    print(f"log: {value}")

s = Subject()
s.subscribe(log_observer)
s.notify("merhaba")

Expected output

log: merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Where does the Subject keep subscribers in the Observer pattern?

  • In a set
  • In a file
  • In a list Correct answer
  • In a database

Explanation: The Subject keeps subscribers in the _observers list.

2 Complete the notify body

Question
    def notify(self, value):
        for obs in self._observers:
            ____(value)
Answer
    def notify(self, value):
        for obs in self._observers:
            obs(value)

Explanation: obs(value) calls each subscriber.

3 Match the Observer concepts

Term Meaning
Subject Notifies
subscribe Adds a subscriber
notify Informs
obs(value) Calls a subscriber

All lessons in Advanced