Build an Event Dispatcher with Subscribe and Notify Operations
Data Structure DesignModel answerLast updated
Design and implement a subscription-based event system where functions can subscribe to event identifiers and be invoked when those events are triggered.
Design and implement an event dispatch mechanism for a single-threaded application. The system allows functions to subscribe to specific event identifiers and be notified when those events occur.
Your implementation must provide three operations:
def register_callback(id, callback) -> None: ...
def unregister_callback(id, callback) -> None: ...
def signal(id) -> None: ...
Where callback can be any callable object in Python.
Example usage:
register_callback(10, handler_a)
register_callback(10, handler_b)
signal(10) # invokes handler_a and handler_b
unregister_callback(10, handler_b)
signal(10) # invokes only handler_a
signal(200) # does nothing since no handlers are registered
Requirements:
- All three functions must return
None - Triggering an event with no subscribers should proceed without error
- Assume single-threaded execution unless told otherwise
Key Design Questions to Consider:
Before implementing, think through:
- Should
signalpass any arguments to the handlers it invokes? - If a handler is registered multiple times for the same event, should it execute once or multiple times? How should removal work in that case?
- What should happen when attempting to remove a handler that was never registered?
- Must handlers execute in a predictable order?
- If a handler throws an exception, should subsequent handlers still run?
- Can a handler itself trigger events? What happens if this creates a cycle?
Your solution should handle these edge cases with explicit, reasoned policies rather than leaving behavior undefined.
Hints
Hint 1
What data structure allows efficient lookup by event ID while maintaining handler ordering?
Hint 2
Consider which Python callables are hashable and which are not (lambdas, bound methods, partials).
Hint 3
Think about reentrancy: a handler calling signal() could create infinite recursion if not detected.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
This problem tests your ability to design a clean API while reasoning through edge cases and failure modes. The code itself is straightforward; the value is in asking clarifying questions and defending your design choices.
Clarifying Questions and Design Decisions
Arguments to handlers: I'll assume signal passes no arguments. If arguments are needed, we'd add signal(id, *args, **kwargs).
Duplicate registrations: If the same handler is registered twice, I'll allow it to run twice. A single unregister_callback removes only one registration. This mirrors how event systems like DOM listeners work.
Unknown removals: Attempting to remove a non-existent handler will be a no-op. Raising an error would force callers to track registration state, adding unnecessary complexity.
Execution order: Handlers run in registration order. This makes behavior predictable and easier to reason about.
Exception handling: If a handler raises an exception, I'll catch it, allow remaining handlers to run, and re-raise the first exception after all handlers complete. This prevents one broken handler from blocking others while still surfacing errors to the caller.
Reentrancy: I'll detect cycles by tracking the dispatch stack. If signal(id) is called while already dispatching for that same id, I'll raise an error to prevent infinite recursion.
Implementation
from typing import Callable, Dict, List
class EventDispatcher:
def __init__(self):
# Use lists to maintain registration order and allow duplicates
self._handlers: Dict[int, List[Callable]] = {}
# Track active dispatches to detect reentrancy
self._dispatching: set = set()
def register_callback(self, id: int, callback: Callable) -> None:
"""Subscribe a handler to an event identifier."""
if id not in self._handlers:
self._handlers[id] = []
self._handlers[id].append(callback)
def unregister_callback(self, id: int, callback: Callable) -> None:
"""Remove one registration of a handler from an event."""
if id in self._handlers:
try:
# Remove only the first occurrence
self._handlers[id].remove(callback)
# Clean up empty lists
if not self._handlers[id]:
del self._handlers[id]
except ValueError:
# Handler not found; no-op as designed
pass
def signal(self, id: int) -> None:
"""Trigger all handlers subscribed to this event."""
# Check for reentrancy
if id in self._dispatching:
raise RuntimeError(f"Reentrant signal detected for id {id}")
# No handlers registered; no-op
if id not in self._handlers:
return
# Mark this id as being dispatched
self._dispatching.add(id)
first_exception = None
handlers = self._handlers[id][:] # Copy to avoid modification during iteration
try:
for handler in handlers:
try:
handler()
except Exception as e:
# Capture first error but continue
if first_exception is None:
first_exception = e
finally:
# Always clean up dispatch state
self._dispatching.remove(id)
# Re-raise the first exception after all handlers ran
if first_exception is not None:
raise first_exception
# Global instance for module-level functions
_dispatcher = EventDispatcher()
def register_callback(id: int, callback: Callable) -> None:
_dispatcher.register_callback(id, callback)
def unregister_callback(id: int, callback: Callable) -> None:
_dispatcher.unregister_callback(id, callback)
def signal(id: int) -> None:
_dispatcher.signal(id)
Storage Design and Trade-offs
Why lists instead of sets? Sets require elements to be hashable. While functions and classes are hashable, lambdas created dynamically have unique identities, and bound methods like obj.method create new objects each time. Using a list avoids these constraints and naturally maintains insertion order.
Complexity:
register_callback: O(1)unregister_callback: O(n) where n is handlers for that id (due tolist.remove)signal: O(n) to invoke all handlers
For typical use (few handlers per event), this is efficient. If removal is frequent and handler counts are large, consider a doubly-linked list or a list of (handler, active_flag) pairs.
Exception Handling Rationale
Continuing after exceptions prevents one faulty handler from blocking others. Re-raising the first exception signals that something failed while allowing all handlers to attempt execution. This trades immediate failure detection for robustness.
Alternative: Catch all exceptions, log them, and let signal complete silently. This maximizes robustness but hides errors. The choice depends on whether subscribers are trusted.
Critical exceptions: System-level exceptions like SystemExit and KeyboardInterrupt should not be caught. Modify the except clause to except Exception rather than bare except.
Reentrancy Detection
The _dispatching set tracks which events are currently being handled. Before dispatching, we check if id is already in the set. This prevents direct recursion (signal(10) → handler calls signal(10)).
Cross-event cycles: The current implementation only catches direct recursion. If handler A signals event 20, whose handler signals event 10 again, the check passes. To detect indirect cycles, track a stack of all active dispatches and check for any repeat.
Alternative policies:
- Allow all reentrancy: Remove the check entirely. Risk: infinite recursion if not carefully managed.
- Queue nested signals: Instead of executing immediately, queue them to run after the current dispatch completes. This guarantees termination but changes semantics.
Testing Strategy
def test_basic_flow():
results = []
register_callback(1, lambda: results.append('a'))
register_callback(1, lambda: results.append('b'))
signal(1)
assert results == ['a', 'b']
def test_duplicate_registration():
results = []
handler = lambda: results.append('x')
register_callback(2, handler)
register_callback(2, handler)
signal(2)
assert results == ['x', 'x']
def test_exception_isolation():
results = []
register_callback(3, lambda: results.append('before'))
register_callback(3, lambda: 1/0) # raises
register_callback(3, lambda: results.append('after'))
with pytest.raises(ZeroDivisionError):
signal(3)
assert results == ['before', 'after']
def test_reentrancy_detection():
def recursive_handler():
signal(4) # Tries to trigger same event
register_callback(4, recursive_handler)
with pytest.raises(RuntimeError, match="Reentrant"):
signal(4)
This design balances simplicity, predictability, and robustness while making deliberate choices about edge cases.