Event Emitter (Pub/Sub)

easy
Unit 8 · Dataclasses0/3 to milestone

Decouple parts of an app with events: the code that emits "user_signed_up" doesn't need to know who's listening.

Implement a class EventEmitter:

  • on(event, fn): register a listener and return fn, so callers can keep it to pass to off later.
  • once(event, fn): a listener that runs at most once.
  • off(event, fn): remove a listener. Removing one that isn't registered does nothing.
  • emit(event, *args, **kwargs): call listeners in registration order and return how many were called.
    • Listeners added during an emit don't run in that emit.
    • If a listener raises, still call the rest, then raise the first exception.
#design#callbacks#classes2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Event Emitter (Pub/Sub) · TechGradify