In-Process Event Callback Registry

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Build a lightweight single-threaded, in-process publish/subscribe event dispatcher in Python. Listeners (Callable objects taking zero arguments) subscribe under a hashable event key (id), and firing that key runs its subscribed listeners while isolating runtime failures and preventing infinite dispatch loops.

Implement the CallbackRegistry class alongside three module-level convenience functions backed by a default CallbackRegistry instance:

  • CallbackRegistry(error_handler=log_callback_error)
    • register_callback(id, callback) -> None
    • unregister_callback(id, callback) -> None
    • signal(id) -> None
  • Module-level functions register_callback(id, callback) -> None, unregister_callback(id, callback) -> None, and signal(id) -> None.

Your implementation must enforce all of the following behavioral rules:

  1. Return values and input validation: Every public method and module function returns None; any value returned by a listener is discarded. register_callback must verify callable(callback) immediately and raise TypeError if given a non-callable object.
  2. Callable support, ordering, and duplicates: Listeners for a given id execute in first-in, first-out (FIFO) registration order. Any Python callable must be supported — including plain functions, bound instance methods (obj.method), functools.partial wrappers, lambdas, and unhashable callable instances (classes defining __call__ and __eq__ without __hash__). Registering the same listener k times causes it to run k times per signal(id).
  3. Idempotent unregistration: unregister_callback(id, callback) removes only the earliest matching registration (is or ==) for id. Unsubscribing an unknown id or an unsubscribed callback does nothing (None).
  4. Snapshot dispatch: signal(id) takes a shallow snapshot of id's listener list before invoking any listener so mid-dispatch register_callback or unregister_callback calls take effect starting on the next signal(id) call. Firing an id with zero listeners is a safe no-op.
  5. Failure isolation: If a listener raises an Exception, signal(id) passes (id, callback, exc) to error_handler and continues executing the remaining listeners in the snapshot. Non-Exception subclasses of BaseException (such as KeyboardInterrupt or SystemExit) must propagate out immediately without leaving id stuck in an active state.
  6. Cycle prevention (ReentrantSignalError): A listener may legitimately call signal(other_id) for a distinct inactive key, forming acyclic chains. However, calling signal(id) while id is already mid-dispatch anywhere on the current call stack — either directly (id -> id) or indirectly (k1 -> k2 -> k1) — must immediately raise ReentrantSignalError.

Examples

Example 1

Input:

events = []

def record_audit():
    events.append("audit")

def send_alert():
    events.append("alert")

register_callback(42, record_audit)
register_callback(42, send_alert)
signal(42)
unregister_callback(42, send_alert)
signal(42)
signal(999)

Output:

# Every call returns None, and `events` ends up as:
["audit", "alert", "audit"]

Walk-through: Subscribing record_audit then send_alert under key 42 and calling signal(42) runs both in FIFO order (["audit", "alert"]). After unregister_callback(42, send_alert), the second signal(42) runs only record_audit (["audit", "alert", "audit"]), and signal(999) is a no-op because key 999 has no subscribers.

Example 2

Input:

logged_errors = []
trace = []
reg = CallbackRegistry(error_handler=lambda sig, cb, exc: logged_errors.append((sig, type(exc).__name__)))

reg.register_callback("sync", lambda: trace.append("start"))
reg.register_callback("sync", lambda: (_ for _ in ()).throw(ValueError("bad row")))
reg.register_callback("sync", lambda: (trace.append("finish"), reg.signal("notify")))
reg.register_callback("notify", lambda: trace.append("notified"))
reg.signal("sync")

reg.register_callback("s1", lambda: (trace.append("s1"), reg.signal("s2")))
reg.register_callback("s2", lambda: (trace.append("s2"), reg.signal("s1")))
reg.signal("s1")

Output:

# trace:
["start", "finish", "notified", "s1", "s2"]

# logged_errors:
[("sync", "ValueError"), ("s2", "ReentrantSignalError")]

Walk-through: During reg.signal("sync"), the second listener raises ValueError, which is reported to error_handler while the third listener still runs and chains cleanly into "notify". Next, reg.signal("s1") chains into "s2", whose attempt to re-trigger active key "s1" raises ReentrantSignalError; "s2"'s dispatch loop reports that error and unwinds cleanly without infinite recursion.

Constraints

  • id is any hashable Python object (int, str, tuple, enum, etc.).
  • callback may be any callable object (not necessarily hashable); non-callable values passed to register_callback must raise TypeError.
  • Single-threaded execution may be assumed for the core implementation.
  • Up to 10^4 total registrations and signal invocations per test run.

Step-by-step walkthrough

  1. Clarify the contract before writing code

    A publish/subscribe (pub/sub) registry is an event board where listener functions ("subscribers" or callbacks) sign up under a topic key (id), and firing that key (signal(id)) invokes every function signed up for it.

    Because the implementation is compact, the real design work is locking down crisp, defensible rules for every ambiguous interaction up front:

    Design question Chosen rule Why this rule makes sense
    What arguments does signal(id) pass to listeners? Zero arguments: callback() signal(id) carries no payload. Callers needing context can bind arguments via functools.partial(fn, id).
    What if the same listener subscribes twice under one id? Keep both; invoke twice; one unregister_callback removes the earliest copy Two subsystems may register the same helper independently; one subsystem cleaning up should not silently disable the other.
    What if unregister_callback receives an unknown id or listener? Safe no-op (return None) Makes finally and teardown blocks idempotent (safe to execute repeatedly without crashing).
    Which types are valid for id and callback? id is hashable; callback is any callable id serves as a dictionary key. Checking callable(callback) eagerly catches bad inputs at registration rather than mid-dispatch.
    Where do listener exceptions go when signal() returns None? Forward (id, callback, exc) to error_handler Prevents one broken listener from starving later ones while surfacing failures in logs or unit tests.
  2. Why a dictionary of lists beats a dictionary of sets

    We need a per-key container mapping each id to its subscribed listeners. A hashable object has a fixed hash code so Python can place it inside a set or use it as a dict key. Storing listeners inside a set (dict[id, set]) looks tempting for O(1) deletion, yet it breaks three requirements at once:

    1. Unhashable callables crash registration: A custom class defining __call__ and __eq__ (without __hash__) is a valid Python callable (any object invocable with ()), yet Python marks it unhashable, so set.add(cb) raises TypeError: unhashable type.
    2. Duplicates vanish: Subscribing [f, g, f] in a set silently drops the second f.
    3. No FIFO ordering guarantee: Python's set does not preserve insertion order, whereas callers expect FIFO execution.

    Using Dict[Hashable, List[Callable]] handles all three cleanly. When removing a listener from the list, we check identity (is) followed by equality (==). In Python, evaluating obj.method allocates a fresh bound method wrapper (pairing self with the underlying function) on every attribute access:

    Lookup 1:  register_callback(42, counter.hit)    -> creates wrapper_A(self=counter, func=hit)
    Lookup 2:  unregister_callback(42, counter.hit)  -> creates wrapper_B(self=counter, func=hit)
    
    wrapper_A is wrapper_B   -> False  (distinct wrapper allocations!)
    wrapper_A == wrapper_B   -> True   (same `self` and same underlying function)
    

    Note that two separate lambda expressions or two functools.partial(tag, "p") instances compare by identity (== is False), so callers using lambdas or partials must hold onto the exact object they registered.

    Operation              Cost     Work done (m = listeners subscribed to that id)
    register_callback      O(1)*    dict lookup + list append (*amortized)
    unregister_callback    O(m)     scan at most m items on that id + list delete
    signal                 O(m)     copy the m-item list + invoke each listener
    
  3. Implement registration and safe unregistration

    Encapsulate state inside CallbackRegistry so tests can instantiate isolated registries with custom error recorders, and expose the three module-level functions delegating to a shared _registry.

    Inside unregister_callback, checking registered_cb is callback before registered_cb == callback mirrors Python's list.remove: fast pointer check first, value equality second. When the last listener for an id is deleted, remove id from self._callbacks so retired keys do not accumulate in memory.

    class CallbackRegistry:
        def __init__(self, error_handler: Callable = log_callback_error) -> None:
            # _callbacks: maps signal_id -> list of callables in registration order,
            # e.g. {42: [record_audit, send_alert], "sync": [on_finish]}
            self._callbacks: Dict[Hashable, List[Callable]] = {}
    
            # _in_flight: set of signal_ids currently mid-dispatch on the call stack,
            # e.g. {"s1", "s2"}, used to catch direct (42 -> 42) and indirect (s1 -> s2 -> s1) cycles
            self._in_flight: Set[Hashable] = set()
    
            # _error_handler: side-channel callback invoked as error_handler(id, callback, exc)
            # because signal() itself must return None
            self._error_handler = error_handler
    
        def register_callback(self, id: Hashable, callback: Callable) -> None:
            # Validate eagerly so non-callable values fail at registration time, not inside signal().
            if not callable(callback):
                raise TypeError(f"callback must be callable, got {callback!r}")
    
            if id not in self._callbacks:
                self._callbacks[id] = []
            self._callbacks[id].append(callback)
    
        def unregister_callback(self, id: Hashable, callback: Callable) -> None:
            callbacks = self._callbacks.get(id)
            if callbacks is None:
                # Unknown id is a safe no-op so cleanup/teardown code can run multiple times safely.
                return
    
            # Scan in order so one unregister removes only the earliest matching registration.
            for index, registered_cb in enumerate(callbacks):
                # Check `is` first, then `==`: accessing `obj.method` creates a new bound-method
                # object each time (`is` is False), whereas `==` compares (self, underlying_func).
                if registered_cb is callback or registered_cb == callback:
                    del callbacks[index]
                    break
    
            # Remove empty lists so unused signal ids do not accumulate in memory over time.
            if not callbacks:
                del self._callbacks[id]
    
  4. Isolate failing callbacks without breaking Ctrl-C

    Consider what happens when the middle listener in [on_start, broken_sync, on_finish] raises ValueError("bad row"):

    • Abort and re-raise: on_finish never executes, and the publisher calling signal() crashes because of an unrelated subscriber.
    • Swallow silently (pass): on_finish executes, but the defect in broken_sync vanishes without a trace.
    • Isolate and report (chosen policy): catch the error around each individual callback(), pass (id, callback, exc) to self._error_handler, and continue the loop so on_finish still runs. By default, log_callback_error logs the full traceback.

    Be selective about which exceptions are caught. In Python's hierarchy, application errors (ValueError, KeyError, RuntimeError) inherit from Exception, whereas process-termination interrupts (KeyboardInterrupt on Ctrl-C and SystemExit) inherit directly from BaseException. Catching Exception isolates broken listeners while allowing Ctrl-C to halt the process immediately.

    class ReentrantSignalError(RuntimeError):
        """signal(id) was called while the same id was already being dispatched."""
    
    
    def log_callback_error(signal_id: Hashable, callback: Callable, exc: Exception) -> None:
        """Default error handler: log the failure with its traceback and carry on."""
        logger.error("callback %r for signal %r raised", callback, signal_id, exc_info=exc)
    
  5. Stop infinite loops with a snapshot and an in-flight set

    Two subtle hazards arise while signal(id) is mid-way through invoking its listeners:

    1. Mid-dispatch subscription edits. Suppose [once, h] are subscribed, and once calls unregister_callback(1, once) while executing. Iterating directly over the live list shifts h left from index 1 to index 0 right before the loop advances to index 1 — skipping h completely!

    Live list mutation bug:
      start:   callbacks = [once, h]    loop at index 0 -> runs once()
      inside:  del callbacks[0]         callbacks is now [h] (h shifted to index 0!)
      next:    loop moves to index 1    past the end -> h never runs!
    
    Snapshot fix:
      start:   snapshot = [once, h]     live self._callbacks[1] can change freely;
               current signal finishes [once, h], and edits apply on the NEXT signal(1).
    

    2. Reentrant dispatch cycles. Reentrancy occurs when a routine is invoked again before an earlier invocation has finished. Chaining distinct keys ("sync" triggers "notify" in Example 2) is useful, whereas re-firing a key that is still active on the call stack — directly (42 -> 42) or indirectly ("s1" -> "s2" -> "s1") — recurses endlessly until RecursionError.

    We guard active keys using self._in_flight: - Before iterating snapshot, check if id in self._in_flight: and raise ReentrantSignalError. - Otherwise add id to self._in_flight, run the loop, and discard id inside a finally block so even an uncatchable KeyboardInterrupt cleans up the active marker.

    Why every signal() call is guaranteed to terminate over K registered keys: - Each nested signal(next_id) either hits an empty key (returns immediately), hits a key already in _in_flight (raises ReentrantSignalError immediately), or adds one hitherto-inactive key to _in_flight. - Since _in_flight can hold at most K keys simultaneously, call depth is bounded by K, and each frame iterates over a finite snapshot list.

        def signal(self, id: Hashable) -> None:
            # Reject reentrant cycles if this id is already active on the current call stack.
            if id in self._in_flight:
                raise ReentrantSignalError(f"signal {id!r} is already being dispatched")
    
            callbacks = self._callbacks.get(id)
            if not callbacks:
                return
    
            # Iterate over a shallow copy so register/unregister calls inside a callback
            # take effect on the next signal() instead of shifting indices mid-loop.
            snapshot = list(callbacks)
    
            # Always clear the in-flight mark in `finally` so an uncatchable BaseException
            # (like KeyboardInterrupt) cannot leave this id permanently locked out.
            self._in_flight.add(id)
            try:
                for callback in snapshot:
                    try:
                        callback()
                    except Exception as exc:
                        # Catch Exception (not BaseException) so one broken callback cannot
                        # starve later ones, while Ctrl-C and SystemExit still propagate.
                        self._error_handler(id, callback, exc)
            finally:
                self._in_flight.discard(id)
    
  6. Trace Example 1 and Example 2 step by step

    First, trace Example 1 (42 and 999):

    Call                                   _callbacks                       _in_flight   What runs
    register_callback(42, record_audit)    {42: [record_audit]}             set()        -
    register_callback(42, send_alert)      {42: [record_audit, send_alert]} set()        -
    signal(42)                             {42: [record_audit, send_alert]} {42} -> {}   record_audit(), send_alert()
    unregister_callback(42, send_alert)    {42: [record_audit]}             set()        -
    signal(42)                             {42: [record_audit]}             {42} -> {}   record_audit()
    signal(999)                            {42: [record_audit]}             set()        nothing (no-op)
    

    Second, trace the "s1" -> "s2" -> "s1" cycle from Example 2:

    1. reg.signal("s1")      _in_flight = {"s1"}         runs cb_s1() -> appends "s1", calls reg.signal("s2")
    2.   reg.signal("s2")    _in_flight = {"s1", "s2"}   runs cb_s2() -> appends "s2", calls reg.signal("s1")
    3.     reg.signal("s1")  "s1" is in _in_flight!      -> raises ReentrantSignalError
    4.   "s2" loop catches ReentrantSignalError -> error_handler("s2", cb_s2, err)
    5.   finally discards "s2", then outer finally discards "s1" -> _in_flight = set(), returns None
    
  7. Complete solution

    from typing import Callable, Dict, Hashable, List, Set
    import logging
    
    logger = logging.getLogger(__name__)
    
    
    class ReentrantSignalError(RuntimeError):
        """signal(id) was called while the same id was already being dispatched."""
    
    
    def log_callback_error(signal_id: Hashable, callback: Callable, exc: Exception) -> None:
        """Default error handler: log the failure with its traceback and carry on."""
        logger.error("callback %r for signal %r raised", callback, signal_id, exc_info=exc)
    
    
    class CallbackRegistry:
        def __init__(self, error_handler: Callable = log_callback_error) -> None:
            # _callbacks: maps signal_id -> list of callables in registration order,
            # e.g. {42: [record_audit, send_alert], "sync": [on_finish]}
            self._callbacks: Dict[Hashable, List[Callable]] = {}
    
            # _in_flight: set of signal_ids currently mid-dispatch on the call stack,
            # e.g. {"s1", "s2"}, used to catch direct (42 -> 42) and indirect (s1 -> s2 -> s1) cycles
            self._in_flight: Set[Hashable] = set()
    
            # _error_handler: side-channel callback invoked as error_handler(id, callback, exc)
            # because signal() itself must return None
            self._error_handler = error_handler
    
        def register_callback(self, id: Hashable, callback: Callable) -> None:
            # Validate eagerly so non-callable values fail at registration time, not inside signal().
            if not callable(callback):
                raise TypeError(f"callback must be callable, got {callback!r}")
    
            if id not in self._callbacks:
                self._callbacks[id] = []
            self._callbacks[id].append(callback)
    
        def unregister_callback(self, id: Hashable, callback: Callable) -> None:
            callbacks = self._callbacks.get(id)
            if callbacks is None:
                # Unknown id is a safe no-op so cleanup/teardown code can run multiple times safely.
                return
    
            # Scan in order so one unregister removes only the earliest matching registration.
            for index, registered_cb in enumerate(callbacks):
                # Check `is` first, then `==`: accessing `obj.method` creates a new bound-method
                # object each time (`is` is False), whereas `==` compares (self, underlying_func).
                if registered_cb is callback or registered_cb == callback:
                    del callbacks[index]
                    break
    
            # Remove empty lists so unused signal ids do not accumulate in memory over time.
            if not callbacks:
                del self._callbacks[id]
    
        def signal(self, id: Hashable) -> None:
            # Reject reentrant cycles if this id is already active on the current call stack.
            if id in self._in_flight:
                raise ReentrantSignalError(f"signal {id!r} is already being dispatched")
    
            callbacks = self._callbacks.get(id)
            if not callbacks:
                return
    
            # Iterate over a shallow copy so register/unregister calls inside a callback
            # take effect on the next signal() instead of shifting indices mid-loop.
            snapshot = list(callbacks)
    
            # Always clear the in-flight mark in `finally` so an uncatchable BaseException
            # (like KeyboardInterrupt) cannot leave this id permanently locked out.
            self._in_flight.add(id)
            try:
                for callback in snapshot:
                    try:
                        callback()
                    except Exception as exc:
                        # Catch Exception (not BaseException) so one broken callback cannot
                        # starve later ones, while Ctrl-C and SystemExit still propagate.
                        self._error_handler(id, callback, exc)
            finally:
                self._in_flight.discard(id)
    
    
    _registry = CallbackRegistry()
    
    
    def register_callback(id, callback) -> None:
        _registry.register_callback(id, callback)
    
    
    def unregister_callback(id, callback) -> None:
        _registry.unregister_callback(id, callback)
    
    
    def signal(id) -> None:
        _registry.signal(id)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of this registry like an office dispatch board organized by event code (id), where each event code holds a numbered sign-up sheet of listener functions (callbacks) to invoke in the exact order they subscribed.

A naive implementation drops listeners into a Python set and loops directly over that container inside signal(id). That fails immediately: a set crashes with TypeError on unhashable callable objects (objects without a fixed hash code), loses sign-up order, and silently collapses intentional duplicate subscriptions. Worse, iterating over a live list skips the next listener whenever an executing listener unsubscribes itself, and allowing a listener to re-fire an event code that is still mid-dispatch causes unbounded recursion.

Instead, we map id -> list[Callable], copy that list into a snapshot (a shallow copy frozen at the start of dispatch) before invoking anything, wrap each invocation in try ... except Exception so one crash cannot starve later subscribers, and track active dispatches in an _in_flight set. For example, with [record_audit, send_alert] subscribed under key 42: 1. signal(42) checks 42 in _in_flight (False), copies snapshot = [record_audit, send_alert], and adds 42 to _in_flight. 2. If record_audit() accidentally calls signal(42) again, the nested call sees 42 in _in_flight and raises ReentrantSignalError. 3. The outer loop catches that Exception, forwards (42, record_audit, err) to error_handler, still executes send_alert(), and discards 42 from _in_flight inside finally.

Complexity

  • register_callback: O(1) amortized time. One dictionary lookup by id plus an amortized constant-time list.append.
  • unregister_callback: O(m) time, where m is the number of listeners registered under that specific id. In the worst case we scan all m entries on that id to locate the earliest match and shift subsequent pointers left on del, never touching other event keys.
  • signal: O(m) dispatch overhead (plus the runtime of the m listeners themselves). Membership checks and updates on _in_flight take O(1) set operations, and list(callbacks) copies m callable references once prior to looping.
  • Space: O(N + K) overall, where N is the total number of active listener registrations across K active event keys (plus at most K keys inside _in_flight during nested chains). Empty lists are pruned on unregistration so retired keys consume zero memory.

Edge cases

  • Signaling an unknown key (signal(999)): _callbacks.get(999) is None, so signal returns None immediately without error.
  • Duplicate subscriptions ([f, g, f]): signal invokes f, then g, then f. One unregister_callback removes only the earliest f, leaving [g, f].
  • Unsubscribing an unknown key or listener: safely ignored as a no-op, including when f is subscribed under key 1 and the caller unsubscribes (2, f).
  • Bound methods (obj.method): every attribute evaluation obj.method allocates a fresh bound method wrapper (obj.method is obj.method is False), so unregister_callback falls back to == to compare the underlying (self, function) pair.
  • Lambdas and functools.partial: two separate lambda or partial(tag, "p") instances compare by object identity, so callers must retain the exact object they passed to register_callback if they later wish to unsubscribe it.
  • Unhashable callable instances: a class defining __call__ and __eq__ (which sets __hash__ = None in Python) works smoothly because listeners live in lists rather than sets or dict keys.
  • KeyboardInterrupt and SystemExit: because the dispatch loop catches Exception rather than BaseException, process-level interrupts propagate out immediately while finally still removes id from _in_flight.
  • Unbounded chains of newly minted keys: if listener n dynamically registers and fires key n + 1 forever, _in_flight sees no repeated key and Python eventually raises RecursionError (caught as an Exception). Enforcing if len(self._in_flight) >= MAX_DEPTH: converts that into an immediate ReentrantSignalError.

Common mistakes

  • Storing listeners in a set: loses FIFO order, collapses valid duplicate subscriptions, and raises TypeError on unhashable callable instances.
  • Checking only is in unregister_callback: unregister_callback(42, counter.hit) fails to match the earlier counter.hit wrapper, leaving the listener subscribed forever.
  • Iterating directly over self._callbacks[id] without list(...): if listener i unsubscribes itself, element i + 1 shifts left into index i and gets skipped on the next iteration.
  • Using bare except: or except BaseException:: swallows KeyboardInterrupt (Ctrl-C) and SystemExit inside the dispatch loop.
  • Clearing _in_flight outside a finally block: if an uncatchable BaseException escapes mid-dispatch, id remains stuck in _in_flight and every future signal(id) falsely raises ReentrantSignalError.
  • Forbidding all nested signal() calls: a single boolean _dispatching flag breaks valid multi-stage pipelines such as "sync" -> "notify". Tracking a set of active keys blocks cycles while permitting acyclic chains.

Alternative approaches

  • Subscription token / handle: register_callback returns an opaque integer ID (or a Subscription object with .cancel()), enabling O(1) unsubscription and unambiguous removal of inline lambdas — traded off here because the API requires register_callback to return None.
  • Ordered count map (dict[id, dict[Callable, int]]): gives O(1) unsubscription and preserves first-seen order, but rejects unhashable callables and alters interleaved duplicates ([f, g, f] executes as f, f, g).
  • Strict unsubscription errors: raising KeyError or ValueError when unregister_callback finds no match catches caller typos early, at the expense of idempotent finally cleanup.

Follow-up questions

  • Suppose an active listener unsubscribes itself—or subscribes a new listener to the same signal key—mid-dispatch. How does your design behave, and when would you tighten that contract? Because signal loops over snapshot = list(callbacks) captured before the first listener runs, both self-unsubscription and new subscriptions take effect starting on the next signal(id) call, eliminating index-shift skips. The one subtlety is when listener A unsubscribes listener B mid-dispatch: under pure snapshot semantics, B still executes one final time in the in-progress batch. When strict "never fires once unregister_callback returns" guarantees are needed, wrap each listener in a small _Slot(callback, active=True) record — unregister_callback sets slot.active = False and deletes it from the live list, while signal checks if slot.active: before calling each snapshot slot.

python class _Slot: def __init__(self, callback: Callable) -> None: self.callback = callback self.active = True # cleared on unregister so in-progress snapshots skip it

  • How would you adapt this registry for multi-threaded callers without risking deadlocks when a listener re-enters the registry? Guard self._callbacks with a mutex lock (threading.Lock, a synchronization primitive allowing only one thread at a time to read or mutate shared state), hold that lock only while copying snapshot = list(callbacks), and release it before invoking any user listener. Never invoke arbitrary subscriber code while holding a lock: even with a reentrant lock (threading.RLock, which the owning thread can re-acquire), two threads cross-signaling or waiting on each other inside listeners will deadlock. Equally important, move _in_flight into thread-local storage (threading.local(), giving each OS thread its own isolated active set), since Thread A and Thread B firing key 42 simultaneously is concurrent execution rather than a recursive loop.

  • Storing normal references to bound methods prevents their owning instances from being garbage-collected. How can you eliminate that retention leak, and what caveats appear? A weak reference tracks an object without preventing Python's garbage collector from reclaiming it once all normal references disappear. You can wrap bound methods with weakref.WeakMethod(cb) (note that plain weakref.ref(obj.method) dies immediately because the temporary bound-method wrapper has no other owner!) and regular callables with weakref.ref(cb), dereferencing each entry during signal and pruning dead references that return None. Two caveats follow: ephemeral callables passed inline — such as register_callback(42, lambda: ...) or an unsaved functools.partial — have zero external owners and get collected right away without ever firing, and classes using __slots__ without "__weakref__" raise TypeError. Consequently, production event buses keep strong references by default and expose an explicit weak=True option.

Follow-up questions

Similar questions

More Candid Health interview questions

All 1 Candid Health questions →