Skip to content

Manager

minevent.manager

Implement the event manager.

minevent.manager.EventManager

Implement an event manager.

This event manager allows registering event handlers and triggering events. An event is represented by a case-sensitive string. Each event can have multiple handlers attached, and all handlers are executed in the order they were added when the event is triggered.

add_event_handler (or the on decorator) registers an event handler and returns a Subscription that removes that registration. trigger_event runs the handlers synchronously, and atrigger_event awaits the coroutine handlers. The manager has no global state: create one instance and pass it where it is needed. Registrations and triggers are logged at the DEBUG level by the minevent.manager logger.

Error policy: handlers run fail-fast. If a handler raises, the exception propagates to the caller of trigger_event (or atrigger_event) and the remaining handlers of that event are not executed.

Thread safety: the registration, removal and inspection of handlers are protected by a reentrant lock, and trigger_event runs the handlers on a snapshot taken under the lock, outside of it. So handlers can be registered in one thread and events triggered from worker threads. The handlers themselves run in the thread that triggers the event, concurrently if several threads trigger the same event, so a handler that shares state must be thread-safe. The mutable state of a condition, such as the counter of PeriodicCondition, is not protected.

A manager is a service, not a collection: bool(manager) is always True, even when it has no handler, so manager or default means "is there a manager". Use len(manager) for the number of registrations. A manager owns a lock and a registry, so it cannot be copied or pickled (copy.copy, copy.deepcopy and pickle raise a TypeError): create a new one.

Example
>>> from minevent import EventHandler, EventManager
>>> def hello_handler():
...     print("Hello!")
...
>>> manager = EventManager()
>>> bool(manager)
True
>>> _ = manager.add_event_handler("my_event", EventHandler(hello_handler))
>>> manager.trigger_event("my_event")
Hello!

minevent.manager.EventManager.events property

events: list[str]

Get the events that have at least one registered handler.

Returns:

Type Description
list[str]

The event names, in the order they were first registered.

Example
>>> from minevent import EventHandler, EventManager
>>> manager = EventManager()
>>> manager.events
[]
>>> _ = manager.add_event_handler("my_event", EventHandler(print))
>>> manager.events
['my_event']
>>> "my_event" in manager
True

minevent.manager.EventManager.add_event_handler

add_event_handler(
    event: str,
    event_handler: BaseEventHandler,
    *,
    once: bool = False,
) -> Subscription

Add an event handler to an event.

The event handler will be called every time the specified event is triggered. Multiple handlers can be registered to the same event, and they will be executed in the order they were added.

Parameters:

Name Type Description Default
event str

The event name (case-sensitive string) to which the event handler should be attached.

required
event_handler BaseEventHandler

The event handler instance to attach to the event.

required
once bool

If True, the handler is removed before its first execution, so it runs at most once. The registration is removed by the next trigger even if the condition of the handler is False and the handler function is not called. Default is False.

False

Returns:

Type Description
Subscription

A subscription whose remove method removes this registration only.

Raises:

Type Description
TypeError

if event is not a string, or if event_handler is not a BaseEventHandler. Wrap a function with EventHandler.

Example
>>> from minevent import EventManager, EventHandler
>>> def hello_handler():
...     print("Hello!")
...
>>> manager = EventManager()
>>> subscription = manager.add_event_handler("my_event", EventHandler(hello_handler))
>>> manager.trigger_event("my_event")
Hello!
>>> subscription.remove()
True
>>> manager.trigger_event("my_event")
>>> _ = manager.add_event_handler("my_event", EventHandler(hello_handler), once=True)
>>> manager.trigger_event("my_event")
Hello!
>>> manager.trigger_event("my_event")

minevent.manager.EventManager.atrigger_event async

atrigger_event(event: str, /, **payload: object) -> None

Trigger the handler(s) for the given event, awaiting the coroutine handlers.

This method behaves like trigger_event, but it calls ahandle on the event handlers, so handlers that are coroutine functions (or return an awaitable) are awaited. Synchronous handlers can be mixed with coroutine handlers. The handlers run one after the other, in the order they were added, and they are fail-fast like in trigger_event: the exception is not wrapped and has a note with the event and the handler. The snapshot of the handlers, the once registrations and the payload follow the rules of trigger_event. Synchronous handlers block the event loop while they run.

Parameters:

Name Type Description Default
event str

The event name (case-sensitive string) to trigger.

required
**payload object

The data passed to the handlers as keyword arguments.

{}

Raises:

Type Description
TypeError

if event is not a string. Any exception raised by a handler also propagates.

Example
>>> import asyncio
>>> from minevent import EventHandler, EventManager
>>> manager = EventManager()
>>> async def hello_handler(name):
...     print(f"Hello {name}!")
...
>>> _ = manager.add_event_handler("my_event", EventHandler(hello_handler))
>>> asyncio.run(manager.atrigger_event("my_event", name="John"))
Hello John!

minevent.manager.EventManager.clear_event

clear_event(event: str) -> None

Remove all the event handlers of a given event.

Nothing happens if the event has no registered handler. The subscriptions of the removed handlers become inactive.

Parameters:

Name Type Description Default
event str

The event name (case-sensitive string) to clear.

required

Raises:

Type Description
TypeError

if event is not a string.

Example
>>> from minevent import EventHandler, EventManager
>>> manager = EventManager()
>>> _ = manager.add_event_handler("my_event", EventHandler(print))
>>> manager.clear_event("my_event")
>>> manager.events
[]

minevent.manager.EventManager.get_subscriptions

get_subscriptions(event: str) -> tuple[Subscription, ...]

Get the subscriptions registered for an event.

Parameters:

Name Type Description Default
event str

The event name (case-sensitive string).

required

Returns:

Type Description
tuple[Subscription, ...]

A snapshot of the subscriptions, in the order the handlers run. It is empty if no handler is registered. Use the event_handler property of a subscription to get its handler. Changing the manager does not change the returned tuple.

Raises:

Type Description
TypeError

if event is not a string.

Example
>>> from minevent import EventHandler, EventManager
>>> manager = EventManager()
>>> manager.get_subscriptions("my_event")
()
>>> handler = EventHandler(print)
>>> subscription = manager.add_event_handler("my_event", handler)
>>> manager.get_subscriptions("my_event") == (subscription,)
True
>>> subscription.event_handler is handler
True
>>> len(manager)
1

minevent.manager.EventManager.on

on(
    event: str,
    *,
    once: bool = False,
    condition: Condition | None = None,
    filter_payload: bool = False,
) -> Callable[[_F], _F]

Create a decorator that registers a function as a handler.

The decorated function is registered as EventHandler(func, condition=condition, filter_payload=filter_payload) and returned unchanged. The function is called with the payload only: use add_event_handler if the handler needs handler_args or handler_kwargs, or if you need the Subscription.

Parameters:

Name Type Description Default
event str

The event name (case-sensitive string).

required
once bool

If True, the handler runs at most once. See add_event_handler. Default is False.

False
condition Condition | None

An optional condition evaluated before the handler. See EventHandler. Default is None.

None
filter_payload bool

If True, only the payload keys that the function accepts are passed to it. See EventHandler. Default is False.

False

Returns:

Type Description
Callable[[_F], _F]

The decorator.

Raises:

Type Description
TypeError

if event is not a string, or if condition is not callable.

Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> @manager.on("my_event")
... def hello_handler(name):
...     print(f"Hello {name}!")
...
>>> manager.trigger_event("my_event", name="Bob")
Hello Bob!
>>> hello_handler("Alice")
Hello Alice!
>>> @manager.on("epoch_end", filter_payload=True)
... def log_epoch(epoch):
...     print(f"epoch {epoch}")
...
>>> manager.trigger_event("epoch_end", epoch=3, loss=0.5)
epoch 3

minevent.manager.EventManager.reset

reset() -> None

Reset the event manager.

This method removes all registered event handlers from the event manager, so their subscriptions become inactive. After calling this method, the event manager returns to its initial state.

Example
>>> # Create an event manager
>>> from minevent import EventManager
>>> manager = EventManager()
>>> # Add an event handler
>>> def hello_handler():
...     print("Hello!")
...
>>> from minevent import EventHandler
>>> _ = manager.add_event_handler("my_event", EventHandler(hello_handler))
>>> manager.trigger_event("my_event")
Hello!
>>> len(manager)
1
>>> # Reset the event manager
>>> manager.reset()
>>> len(manager)
0

minevent.manager.EventManager.trigger_event

trigger_event(event: str, /, **payload: object) -> None

Trigger the handler(s) for the given event.

This method executes all event handlers registered for the specified event in the order they were added. Nothing happens if no handler is registered.

Handlers are executed fail-fast: if a handler raises, the exception propagates and the remaining handlers are skipped. The exception is not wrapped: it has a note (__notes__) with the event and the function of the handler that raised it.

The handlers are read from a snapshot taken when the event is triggered. Handlers added or removed by a running handler take effect on the next trigger, not the current one. A once registration is removed just before its handler runs.

A handler can trigger events, including the event it handles, but nothing stops the recursion: a handler that always triggers its own event raises a RecursionError. Guard the recursive trigger with a condition or a flag.

The keyword arguments payload are passed to every handler as keyword arguments, after the arguments given at registration. Without payload, handlers are called exactly as before. A handler that does not accept the payload raises a TypeError. The payload can use any key, including event and self, because event is positional-only.

Parameters:

Name Type Description Default
event str

The event name (case-sensitive string) to trigger.

required
**payload object

The data passed to the handlers as keyword arguments.

{}

Raises:

Type Description
TypeError

if event is not a string, or if a handler returns an awaitable (use atrigger_event for coroutine handlers). Any exception raised by a handler also propagates.

Example
>>> from minevent import EventHandler, EventManager
>>> manager = EventManager()
>>> manager.trigger_event("my_event")  # do nothing because there is no event handler
>>> def hello_handler():
...     print("Hello!")
...
>>> _ = manager.add_event_handler("my_event", EventHandler(hello_handler))
>>> manager.trigger_event("my_event")
Hello!
>>> def epoch_handler(epoch):
...     print(f"epoch {epoch}")
...
>>> _ = manager.add_event_handler("epoch_end", EventHandler(epoch_handler))
>>> manager.trigger_event("epoch_end", epoch=3)
epoch 3

minevent.manager.Subscription

Represent the registration of an event handler to an event.

A subscription is returned by EventManager.add_event_handler. It is the registration itself: the manager stores it, and it removes exactly the registration that created it. The handler does not need to be re-created to be unsubscribed, other registrations of the same handler are not removed, and registering the same handler twice creates two independent subscriptions.

A subscription is a context manager: the registration is removed when the with block exits.

The constructor is internal: subscriptions are created by the event manager.

Parameters:

Name Type Description Default
manager EventManager

The event manager that stores the registration.

required
event str

The event name of the registration.

required
event_handler BaseEventHandler

The registered event handler.

required
once bool

If True, the registration is removed before its first execution. Default is False.

False
Example
>>> from minevent import EventHandler, EventManager
>>> manager = EventManager()
>>> subscription = manager.add_event_handler("my_event", EventHandler(print))
>>> subscription.event
'my_event'
>>> subscription.active
True
>>> subscription.remove()
True
>>> subscription.remove()
False
>>> subscription.active
False
>>> manager.events
[]
>>> with manager.add_event_handler("my_event", EventHandler(print)):
...     manager.events
...
['my_event']
>>> manager.events
[]

minevent.manager.Subscription.active property

active: bool

Indicate if the registration is still registered.

Returns:

Type Description
bool

True if the event handler is still registered, False if it was removed (by this subscription, by clear_event or reset, or because it was a once registration consumed by a trigger), or if it was never registered in its manager. The answer is read from the registry of the manager.

minevent.manager.Subscription.event property

event: str

Get the event name of the registration.

Returns:

Type Description
str

The event name.

minevent.manager.Subscription.event_handler property

event_handler: BaseEventHandler

Get the registered event handler.

Returns:

Type Description
BaseEventHandler

The event handler.

minevent.manager.Subscription.once property

once: bool

Indicate if the registration is removed before its first execution.

Returns:

Type Description
bool

True if the event handler runs at most once, otherwise False.

minevent.manager.Subscription.remove

remove() -> bool

Remove the registration.

Only this registration is removed, even if the same handler is registered several times to the same event. Calling this method again, or after the registration was removed another way (clear_event, reset, a once trigger), does nothing. It never raises, even for a subscription that was never registered in its manager. The cost does not depend on the number of handlers of the event.

Returns:

Type Description
bool

True if the registration was removed, False if it was already removed.