Skip to content

xtr_event_dispatcher

Let the parts of an application talk through events.

Code dispatches an event object; the listeners registered for its name run from the highest priority down, and any of them can stop the rest. A subscriber declares every event it listens to in one place.

dispatcher = EventDispatcher()
dispatcher.add_listener(OrderPlaced, send_receipt, priority=10)
dispatcher.add_subscriber(AuditSubscriber())

await dispatcher.dispatch(OrderPlaced(42))
  • :class:EventDispatcher — the dispatcher listeners are registered on.
  • :class:CompiledEventDispatcher — one whose listeners are fixed up front, as a container builds it.
  • :class:ImmutableEventDispatcher — one handed out for dispatching only.
  • :class:ScopedEventDispatcher — listeners for one scope, added next to those of a shared dispatcher without changing it.
  • :class:IntrospectableDispatcherInterface — what those two wrap: a dispatcher that dispatches and reads its listeners, nothing more.
  • :class:LazyListener — a listener whose object is built when first needed.
  • :class:GenericEvent — an event with a subject and named arguments.
  • :func:as_event_listener — declare a listener where it is written, for the bundle in :mod:xtr_event_dispatcher.bundle to register.
  • :mod:xtr_event_dispatcher.debug — a dispatcher recording what ran.

The contract — :class:Event, :class:StoppableEventInterface, :class:ListenerIntrospectionInterface, :data:Listener, :func:event_name_of — is re-exported from xtr-event-dispatcher-contracts, so both packages name the same objects. Its narrower EventDispatcherInterface, for code that only dispatches, is imported from there; the one here adds registering listeners.

ListenerCall

ListenerCall = 'Callable[[Listener, Listener, int, tuple[object, ...]], Awaitable[None]]'

Runs one listener for :meth:EventDispatcher.dispatch_through.

Given the listener as registered, what runs — the same, or what a lazy listener built into — how many of the arguments it takes, and the arguments.

SubscribedEvents

SubscribedEvents = 'str | tuple[str, int] | SubscribedListener | list[str | tuple[str, int] | SubscribedListener]'

What a subscriber declares for one event.

One listener is a method name, a (method, priority) pair, or a :class:~xtr_event_dispatcher.subscribed_listener.SubscribedListener; a list of those declares several listeners for the same event.

OrderTarget

OrderTarget = 'str | type | Callable[..., object]'

A listener another one runs before or after.

A class names every listener it provides, a function or method names that one listener, and a "module:Qualified.name" string names either without importing it — so a target from a package that is not installed is simply ignored. A callable object is refused: it has no name of its own to match.

CompiledEventDispatcher

CompiledEventDispatcher(listeners: Mapping[str | type, Sequence[tuple[Listener, int]]])

Bases: EventDispatcher

Dispatches to listeners described once, up front, and refuses any change after.

What a container builds: it knows every listener while it compiles, so it hands them over in one go, usually as :class:~xtr_event_dispatcher.lazy_listener.LazyListener objects so that nothing is built before an event needs it.

dispatcher = CompiledEventDispatcher(
    {
        OrderPlaced: [(LazyListener(mailer_factory, "on_placed"), 10), (audit, 0)],
    }
)

Unlike an :class:~xtr_event_dispatcher.immutable_event_dispatcher.ImmutableEventDispatcher wrapped around a dispatcher, it runs its listeners itself, so the dispatcher a listener receives is this one — and cannot be changed either. A listener that must live for one scope goes on a :class:~xtr_event_dispatcher.scoped_event_dispatcher.ScopedEventDispatcher wrapping it.

Register every listener, event by event, each at its priority.

Listeners sharing a priority run in the order given.

Raises:

add_listener

add_listener(event_name: str | type, listener: Listener, priority: int = 0) -> NoReturn

Refuse: the listeners were fixed when the dispatcher was built.

Raises:

add_subscriber

add_subscriber(subscriber: EventSubscriberInterface) -> NoReturn

Refuse: the listeners were fixed when the dispatcher was built.

Raises:

remove_listener

remove_listener(event_name: str | type, listener: Listener) -> NoReturn

Refuse: the listeners were fixed when the dispatcher was built.

Raises:

remove_subscriber

remove_subscriber(subscriber: EventSubscriberInterface) -> NoReturn

Refuse: the listeners were fixed when the dispatcher was built.

Raises:

EventDispatcher

EventDispatcher()

Bases: EventDispatcherInterface

Runs the listeners of each event, highest priority first.

dispatcher = EventDispatcher()
dispatcher.add_listener(OrderPlaced, send_receipt, priority=10)
dispatcher.add_subscriber(AuditSubscriber())

await dispatcher.dispatch(OrderPlaced(42))

Listeners sharing a priority run in the order they were added. One added while an event is dispatched first runs on the next dispatch; one removed meanwhile does not run for the rest of it. A :class:~xtr_event_dispatcher.lazy_listener.LazyListener is built just before it first runs, so one that a stopped event never reaches is never built — and until then it is the lazy listener, not a bound method, that :meth:get_listeners returns.

Removing obj.method while a lazy listener of the event is still unbuilt cannot tell whether that listener is the one: the removal is kept, and applied when it is built — to the lazy listeners registered at the time of the removal only, never to one added after it.

Start with no listener.

dispatch async

dispatch(event: EventT, event_name: str | type | None = None) -> EventT

Run every listener of the event, highest priority first, and return it.

See the contract's :meth:~xtr_event_dispatcher_contracts.event_dispatcher_interface.EventDispatcherInterface.dispatch.

dispatch_through async

dispatch_through(event: EventT, event_name: str | type | None = None, *, dispatcher: object, call: ListenerCall) -> EventT

Dispatch as :meth:dispatch does, running each listener through call.

For a dispatcher wrapping this one that must see every call — the traceable one times them — without running the listeners itself: which ones run, and in which order, stays this dispatcher's decision.

Parameters:

  • event (EventT) –

    What happened.

  • event_name (str | type | None, default: None ) –

    The name to dispatch under; the event's class when None.

  • dispatcher (object) –

    What listeners receive as the dispatcher — the wrapping one.

  • call (ListenerCall) –

    Runs one listener; see :data:ListenerCall.

get_listeners

get_listeners(event_name: None = None) -> dict[str, list[Listener]]
get_listeners(event_name: str | type) -> list[Listener]
get_listeners(event_name: str | type | None = None) -> dict[str, list[Listener]] | list[Listener]

Return the listeners of one event in the order they run, or of every event.

get_listener_priority

get_listener_priority(event_name: str | type, listener: Listener) -> int | None

Return the priority listener runs at for the event, None when it does not.

has_listeners

has_listeners(event_name: str | type | None = None) -> bool

Tell whether the event — or, given None, any event — has a listener.

add_listener

add_listener(event_name: str | type, listener: Listener, priority: int = 0) -> None

Run listener whenever the event is dispatched, at priority.

A lazy listener that has already been built is registered as what it built into.

Raises:

remove_listener

remove_listener(event_name: str | type, listener: Listener) -> None

Stop running listener for the event; one that was not registered is ignored.

add_subscriber

add_subscriber(subscriber: EventSubscriberInterface) -> None

Add a listener for every method subscriber declares.

Raises:

  • InvalidSubscriberError –

    When a declaration cannot be registered — including before or after without a priority, which only a container can honour.

remove_subscriber

remove_subscriber(subscriber: EventSubscriberInterface) -> None

Remove every listener :meth:add_subscriber added for subscriber.

get_prioritized_listeners

get_prioritized_listeners(event_name: str | type) -> list[tuple[int, Listener]]

Return the event's listeners in the order they run, each with its priority.

A listener registered at two priorities appears at both, which :meth:get_listener_priority cannot say.

EventDispatcherInterface

Bases: EventDispatcherInterface, ListenerIntrospectionInterface, Protocol

The whole dispatcher: dispatching, reading its listeners, and changing them.

Whoever builds a dispatcher registers listeners through this; code that only dispatches should depend on the contract's narrower EventDispatcherInterface instead. Wherever an event name is taken, a class stands for its name.

add_listener

add_listener(event_name: str | type, listener: Listener, priority: int = 0) -> None

Run listener whenever the event is dispatched.

Parameters:

  • event_name (str | type) –

    The event to listen to.

  • listener (Listener) –

    What to call — see :data:~xtr_event_dispatcher_contracts.listener.Listener.

  • priority (int, default: 0 ) –

    Higher runs earlier; listeners sharing a priority run in the order they were added.

Raises:

add_subscriber

add_subscriber(subscriber: EventSubscriberInterface) -> None

Add a listener for every method subscriber declares.

Raises:

remove_listener

remove_listener(event_name: str | type, listener: Listener) -> None

Stop running listener for the event; one that was not registered is ignored.

remove_subscriber

remove_subscriber(subscriber: EventSubscriberInterface) -> None

Remove every listener :meth:add_subscriber added for subscriber.

EventSubscriberInterface

Bases: Protocol

Knows which events it listens to, and which of its methods handles each.

Adding a subscriber to a dispatcher registers one listener per declared method. A listener without a priority runs at 0.

class OrderMailer(EventSubscriberInterface):
    @classmethod
    @override
    def get_subscribed_events(cls) -> Mapping[str | type, SubscribedEvents]:
        return {
            OrderPlaced: "on_placed",
            OrderShipped: ("on_shipped", 10),
            OrderCancelled: ["notify_customer", {"method": "notify_warehouse", "priority": -5}],
        }

A container derives the subscriber's listeners from the class, before any instance exists, so the declaration must not depend on state: put what varies at runtime in the methods it names.

get_subscribed_events classmethod

get_subscribed_events() -> Mapping[str | type, SubscribedEvents]

Map each event — its name, or its class — to the listeners declared for it.

ArgumentNotFoundError

ArgumentNotFoundError(key: str)

Bases: EventDispatcherError, KeyError

A :class:~xtr_event_dispatcher.generic_event.GenericEvent has no such argument.

Also a :class:KeyError, since a generic event is read like a mapping: event["name"] raising it is what any mapping would do.

Attributes:

  • key (str) –

    The argument that was asked for.

Record which argument was asked for.

BadMethodCallError

BadMethodCallError(method: str)

Bases: EventDispatcherError, RuntimeError

A dispatcher was asked to add or remove a listener, and it cannot be changed.

Raised by :class:~xtr_event_dispatcher.immutable_event_dispatcher.ImmutableEventDispatcher, which hands its dispatcher out for dispatching only. A listener that must live for a while only belongs on a :class:~xtr_event_dispatcher.scoped_event_dispatcher.ScopedEventDispatcher wrapping it.

Attributes:

  • method (str) –

    The method that was called.

Record which method was called.

EventDispatcherError

Bases: Exception

Base class for every error raised by this library.

Catch this to handle anything dispatching can go wrong with; catch a subclass to handle one cause. Every subclass carries the data a caller needs as typed attributes and composes its own message from them.

InvalidArgumentError

InvalidArgumentError(reason: str)

Bases: EventDispatcherError, ValueError

A dispatcher, or its configuration, was given an argument it cannot work with.

Also a :class:ValueError, so code already guarding its configuration with except ValueError keeps working.

Attributes:

  • reason (str) –

    What is wrong with the argument.

Record what is wrong with the argument.

InvalidListenerError

InvalidListenerError(listener: str, reason: str)

Bases: EventDispatcherError, ValueError

A listener declared with @as_event_listener, or tagged by hand, cannot be registered.

Raised while the container is built, never on the first event: an event that cannot be told from the listener's signature, a method the class does not have, a dispatcher nobody configured, ordering constraints that contradict each other.

Attributes:

  • listener (str) –

    The listener, as "module:Qualified.name".

  • reason (str) –

    What is wrong with it.

Record which listener is wrong, and why.

InvalidSubscriberError

InvalidSubscriberError(subscriber: str, event_name: str | None, reason: str)

Bases: EventDispatcherError, ValueError

A subscriber's get_subscribed_events() cannot be registered as it stands.

Raised when the subscriber is added, before any of its listeners is: a declaration of an unknown shape, a method the subscriber does not have, or ordering constraints a dispatcher on its own cannot honour.

Attributes:

  • subscriber (str) –

    The subscriber's qualified class name.

  • event_name (str | None) –

    The event whose declaration is wrong; None when what is wrong is not about one event.

  • reason (str) –

    What is wrong with it.

Record which declaration is wrong, and why.

ListenerSignatureError

ListenerSignatureError(listener: str, signature: str)

Bases: EventDispatcherError, TypeError

A callable cannot be called with an event, its name and the dispatcher.

A dispatcher passes at most those three arguments, by position, so a listener may take up to three positional parameters and requires nothing else. Raised when the listener is added — or, for a lazy one, when it is first built — rather than when the event it waits for arrives.

Attributes:

  • listener (str) –

    The listener's qualified name.

  • signature (str) –

    Its parameters, as written.

Record which listener cannot be called, and its parameters.

GenericEvent

GenericEvent(subject: object = None, arguments: Mapping[str, object] | None = None)

Bases: Event, MutableMapping[str, object]

An event about a subject, with arguments read and written like a mapping.

For an event not worth a class of its own: the subject is what the event is about, and the arguments are whatever the dispatcher and its listeners exchange.

event = GenericEvent(order, {"notify": True})
await dispatcher.dispatch(event, "order.saved")
if event["notify"]:
    ...

Two generic events are equal when their subject, arguments and stopped state are; being mutable, one cannot be hashed.

Hold the subject, and a copy of the arguments.

Parameters:

  • subject (object, default: None ) –

    What the event is about, usually an object or a callable.

  • arguments (Mapping[str, object] | None, default: None ) –

    The event's initial arguments.

get_subject

get_subject() -> object

Return what the event is about.

get_argument

get_argument(key: str) -> object

Return the argument named key.

Raises:

set_argument

set_argument(key: str, value: object) -> Self

Set the argument named key, and return the event.

get_arguments

get_arguments() -> dict[str, object]

Return a copy of every argument.

set_arguments

set_arguments(arguments: Mapping[str, object] | None = None) -> Self

Replace every argument with a copy of arguments, and return the event.

has_argument

has_argument(key: str) -> bool

Tell whether the event has an argument named key.

ImmutableEventDispatcher

ImmutableEventDispatcher(dispatcher: IntrospectableDispatcherInterface)

Bases: EventDispatcherInterface

Dispatches through another dispatcher, and refuses every change to its listeners.

A dispatcher shared for a process's lifetime is a poor place for a listener added at runtime: it would outlive the request, message or task that added it. Handing the dispatcher out wrapped in this keeps its listeners to those its builder registered. A listener that must live for one scope goes on a :class:~xtr_event_dispatcher.scoped_event_dispatcher.ScopedEventDispatcher wrapping this one.

dispatcher = EventDispatcher()
dispatcher.add_subscriber(AuditSubscriber())
shared = ImmutableEventDispatcher(dispatcher)

shared.add_listener(OrderPlaced, send_receipt)  # BadMethodCallError

Wrap dispatcher, which keeps dispatching and answering for its listeners.

dispatch async

dispatch(event: EventT, event_name: str | type | None = None) -> EventT

Dispatch through the wrapped dispatcher.

get_listeners

get_listeners(event_name: None = None) -> dict[str, list[Listener]]
get_listeners(event_name: str | type) -> list[Listener]
get_listeners(event_name: str | type | None = None) -> dict[str, list[Listener]] | list[Listener]

Return the wrapped dispatcher's listeners.

get_listener_priority

get_listener_priority(event_name: str | type, listener: Listener) -> int | None

Return the priority the wrapped dispatcher runs listener at.

get_prioritized_listeners

get_prioritized_listeners(event_name: str | type) -> list[tuple[int, Listener]]

Return the wrapped dispatcher's listeners of the event, each with its priority.

has_listeners

has_listeners(event_name: str | type | None = None) -> bool

Tell whether the wrapped dispatcher has a listener for the event.

add_listener

add_listener(event_name: str | type, listener: Listener, priority: int = 0) -> NoReturn

Refuse: the listeners cannot change.

Raises:

add_subscriber

add_subscriber(subscriber: EventSubscriberInterface) -> NoReturn

Refuse: the listeners cannot change.

Raises:

remove_listener

remove_listener(event_name: str | type, listener: Listener) -> NoReturn

Refuse: the listeners cannot change.

Raises:

remove_subscriber

remove_subscriber(subscriber: EventSubscriberInterface) -> NoReturn

Refuse: the listeners cannot change.

Raises:

reset

reset() -> None

Forward a reset to the wrapped dispatcher when it has one, a no-op otherwise.

A trace behind this immutable one is still reset between units of work.

IntrospectableDispatcherInterface

Bases: EventDispatcherInterface, ListenerIntrospectionInterface, Protocol

A dispatcher that also tells which listeners it has.

What :class:~xtr_event_dispatcher.immutable_event_dispatcher.ImmutableEventDispatcher and :class:~xtr_event_dispatcher.scoped_event_dispatcher.ScopedEventDispatcher wrap: both contracts at once, and nothing that changes the listeners — so a wrapper accepts a dispatcher that cannot be changed as readily as one that can, and one written against the contracts alone.

LazyListener

LazyListener(factory: Callable[[], Awaitable[object]], method: str = _CALL)

A method of an object that is only built when an event needs it.

Registering a listener usually means building the object it belongs to — and whatever that object needs — for an event that may never be dispatched. A lazy listener holds a factory instead, awaited the first time the listener is about to run; the method it names is then bound to what the factory returned, and that binding is kept.

dispatcher.add_listener(OrderPlaced, LazyListener(build_mailer, "on_order_placed"))

A dispatcher replaces a lazy listener with the bound method once it has been built, so both identify it afterwards — to remove it, or to ask for its priority. Until then, only the lazy listener itself does.

Dispatches arriving together on one event loop before the first build share it: the first awaits the factory and the others wait for it. Each event loop builds under a lock of its own, so a listener kept for the whole process serves every loop; loops running in different threads may each await the factory once, the first result is kept and the others discarded, so a factory should hand out a shared object, as a container does.

Hold the factory and the method to call on what it builds.

Parameters:

  • factory (Callable[[], Awaitable[object]]) –

    Builds, or fetches, the object the listener belongs to.

  • method (str, default: _CALL ) –

    The method to call on it; "__call__" calls the object itself.

method property

method: str

The method called on the object the factory returns.

resolved property

resolved: Listener | None

The bound listener, once built; None before.

resolve async

resolve() -> Listener

Build the object on the first call, and return the listener bound to it.

With "__call__" for method, the listener is the object itself, so it is the object that identifies the listener afterwards.

ScopedEventDispatcher

ScopedEventDispatcher(dispatcher: IntrospectableDispatcherInterface)

Bases: EventDispatcher

Adds listeners to those of another dispatcher, which is left as it is.

Gives a listener the lifetime of a scope — a request, a console command, a test — when the dispatcher it has to run on is shared, and possibly one that cannot be changed at all.

scoped = ScopedEventDispatcher(shared)
scoped.add_listener(OrderPlaced, collect)
await scoped.dispatch(OrderPlaced(42))  # the shared listeners run too

The first listener added here for an event copies that event's listeners from the wrapped dispatcher, at their priorities, so the two sets interleave by priority. An event nothing was added for here is dispatched by the wrapped dispatcher itself.

Wrap dispatcher, whose listeners keep running for every event.

dispatch async

dispatch(event: EventT, event_name: str | type | None = None) -> EventT

Dispatch here when a listener was added for the event, else through the wrapped one.

dispatch_through async

dispatch_through(event: EventT, event_name: str | type | None = None, *, dispatcher: object, call: ListenerCall) -> EventT

Dispatch through call here, or through the wrapped dispatcher when it can.

A wrapped dispatcher that cannot run its listeners through call — one written against the contracts alone — has the event's listeners copied here first, as adding one here would.

add_listener

add_listener(event_name: str | type, listener: Listener, priority: int = 0) -> None

Run listener for the event here, alongside the wrapped dispatcher's listeners.

get_listeners

get_listeners(event_name: None = None) -> dict[str, list[Listener]]
get_listeners(event_name: str | type) -> list[Listener]
get_listeners(event_name: str | type | None = None) -> dict[str, list[Listener]] | list[Listener]

Return the listeners the event runs, here or in the wrapped dispatcher.

get_listener_priority

get_listener_priority(event_name: str | type, listener: Listener) -> int | None

Return the priority listener runs at, here or in the wrapped dispatcher.

get_prioritized_listeners

get_prioritized_listeners(event_name: str | type) -> list[tuple[int, Listener]]

Return the listeners the event runs, here or in the wrapped one, with priorities.

has_listeners

has_listeners(event_name: str | type | None = None) -> bool

Tell whether the event has a listener here or in the wrapped dispatcher.

reset async

reset() -> None

Forward a reset to the wrapped dispatcher when it has one, a no-op otherwise.

A trace behind this scoped one is still reset between units of work; the scoped dispatcher itself is discarded with its scope. A wrapped reset that is a coroutine is awaited, as the reset contract declares.

SubscribedListener

Bases: TypedDict

A subscriber's listener, with its priority and ordering spelled out.

{"method": "on_order_placed", "priority": 10, "after": [AuditSubscriber]}

before and after place the listener relative to others. A dispatcher on its own cannot honour them — it does not know the other listeners' owners — so it requires a priority beside them; a container, which sees every listener at once, orders by them.