easy +8 pts

Observer pattern lite

Implement a minimal observer/subject system with subscribe, unsubscribe, and notify.

Design a minimal observer pattern. Implement a class `Subject` with the following methods: - `__init__(self)`: initializes internal state with no observers. - `subscribe(self, observer)`: adds `observer` to the notification list. Each observer can be added only once; duplicate subscriptions are silently ignored. - `unsubscribe(self, observer)`: removes `observer` from the list. If not present, do nothing. - `notify(self, value)`: calls every currently subscribed observer with `value` as the single argument, in the order they were subscribed. Observers are callable objects (functions, lambdas, or objects with `__call__`). The class must keep track of subscribers in insertion order.

Constraints

The number of observers is at most 1000. All operations should be O(n) or better.

Example

>>> def a(x): print(f'A:{x}')
>>> def b(x): print(f'B:{x}')
>>> s = Subject()
>>> s.subscribe(a)
>>> s.subscribe(b)
>>> s.notify(1)
A:1
B:1
>>> s.unsubscribe(a)
>>> s.notify(2)
B:2
>>> s.subscribe(a)
>>> s.subscribe(a)  # duplicate ignored
>>> s.notify(3)
B:3
A:3
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a list to store observers in the order they subscribe.
To avoid duplicates, check if the observer is already in the list before appending.
For notify, iterate over a copy of the list to avoid issues if an observer unsubscribes during notification.
You don't need to handle exceptions raised by observers; just call them.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.