Main classes and functions¶
minevent ¶
Contain the main features of the minevent package.
minevent is a minimal event system with three concepts: an event (a
case-sensitive string), an event handler (BaseEventHandler,
EventHandler) and an event manager (EventManager) that stores
the handlers and triggers the events. add_event_handler returns a
Subscription that identifies a registration, and the conditions
(Condition, PeriodicCondition, AfterNCondition) control when
a handler runs. The package has no dependency.
minevent.AfterNCondition ¶
Implement a condition that is False for the first n
calls and True afterwards.
The condition is stateful, like PeriodicCondition: each call
advances the counter, so do not share one instance between
several handlers, and call it from one thread because the counter
is not protected by a lock. Use reset to restart the counter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The number of calls to skip. Must be a non-negative integer. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
ValueError
|
if |
Example
>>> from minevent import AfterNCondition
>>> condition = AfterNCondition(2)
>>> [condition() for _ in range(4)]
[False, False, True, True]
minevent.AfterNCondition.n
property
¶
n: int
Get the number of skipped calls.
Returns:
| Type | Description |
|---|---|
int
|
The number of calls that evaluate to |
minevent.AfterNCondition.reset ¶
reset() -> None
Reset the internal counter, as if the condition was just created.
Example
>>> from minevent import AfterNCondition
>>> condition = AfterNCondition(1)
>>> condition(), condition()
(False, True)
>>> condition.reset()
>>> condition()
False
minevent.BaseEventHandler ¶
Bases: ABC
Define the base class to implement an event handler.
A child class has to implement the handle method. Event
handlers are compared by identity, so they can be put in a set
or used as dict keys. Use the Subscription returned by
EventManager.add_event_handler to identify a registration.
Example
>>> from minevent import EventHandler
>>> def hello_handler() -> None:
... print("Hello!")
...
>>> handler = EventHandler(hello_handler)
>>> handler
EventHandler(handler=<function hello_handler at 0x...>, handler_args=(), handler_kwargs={}, condition=None, filter_payload=False)
>>> handler.handle()
Hello!
minevent.BaseEventHandler.ahandle
async
¶
ahandle(**payload: object) -> None
Handle the event asynchronously.
This method is called by EventManager.atrigger_event. The
default implementation calls handle, so it works for
synchronous event handlers. Child classes that support
coroutines should override it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**payload
|
object
|
The keyword arguments given to
|
{}
|
Example
>>> import asyncio
>>> from minevent import EventHandler
>>> def hello_handler() -> None:
... print("Hello!")
...
>>> asyncio.run(EventHandler(hello_handler).ahandle())
Hello!
minevent.BaseEventHandler.handle
abstractmethod
¶
handle(**payload: object) -> None
Handle the event.
This method executes the logic associated with the event handler. It should be implemented by child classes to define the specific behavior when an event is triggered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**payload
|
object
|
The keyword arguments given to
|
{}
|
Example
>>> from minevent import EventHandler
>>> def hello_handler() -> None:
... print("Hello!")
...
>>> handler = EventHandler(hello_handler)
>>> handler.handle()
Hello!
minevent.Condition ¶
Bases: Protocol
Define the protocol of a condition for EventHandler.
A condition is any function without argument that returns a
boolean: a lambda, a method, or an object with a __call__
method like the conditions of this module. It is called each time
the event is triggered, before the handler, and the handler is
executed only if it returns True. A condition can keep a state
between calls.
To combine conditions, write a function. The function decides
which conditions are evaluated: lambda: a() and b() skips b
when a is False, while lambda: all([a(), b()])
evaluates both, so stateful conditions advance together.
Example
>>> from minevent import EventHandler, PeriodicCondition
>>> condition = PeriodicCondition(freq=3)
>>> handler = EventHandler(print, ["Hello!"], condition=condition)
>>> handler.handle()
Hello!
>>> handler.handle()
>>> handler = EventHandler(print, ["Bye!"], condition=lambda: False)
>>> handler.handle()
minevent.Condition.__call__ ¶
__call__() -> bool
Evaluate the condition given the current state.
Returns:
| Type | Description |
|---|---|
bool
|
|
minevent.EventHandler ¶
Bases: BaseEventHandler
Implement an event handler.
This class wraps a callable function or method and allows it to be
executed as an event handler. The handler can be configured with
positional and keyword arguments that will be passed when the
handler is executed, and with an optional condition. When a
condition is given, the handler is executed only if the condition
evaluates to True. This is useful for scenarios where event
handlers should only run under specific circumstances, such as
periodic execution or state-based triggering.
The handler is called as
handler(*handler_args, **handler_kwargs, **payload), where
payload is the data given when the event is triggered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
Callable[..., object]
|
The callable function or method to be invoked when
the event is triggered (and the condition is |
required |
handler_args
|
Sequence[Any] | None
|
The positional arguments to pass to the handler
when it is called. Default is |
None
|
handler_kwargs
|
Mapping[str, Any] | None
|
The keyword arguments to pass to the handler
when it is called. The dictionary is copied, so changing
it afterwards does not change the handler.
Default is |
None
|
condition
|
Condition | None
|
The condition that controls whether the handler
is executed: a function without argument that returns a
boolean, such as a lambda or a |
None
|
filter_payload
|
bool
|
If |
False
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
Example
>>> from minevent import EventHandler, PeriodicCondition
>>> def hello_handler() -> None:
... print("Hello!")
...
>>> handler = EventHandler(hello_handler)
>>> handler
EventHandler(handler=<function hello_handler at 0x...>, handler_args=(), handler_kwargs={}, condition=None, filter_payload=False)
>>> handler.handle()
Hello!
>>> handler = EventHandler(print, handler_args=["Hello!"])
>>> handler.handle()
Hello!
>>> handler = EventHandler(hello_handler, condition=PeriodicCondition(freq=3))
>>> handler
EventHandler(handler=<function hello_handler at 0x...>, handler_args=(), handler_kwargs={}, condition=PeriodicCondition(freq=3, skip_first=False, step=0), filter_payload=False)
>>> handler.handle()
Hello!
>>> handler.handle()
>>> handler.handle()
>>> handler.handle()
Hello!
>>> def epoch_handler(epoch: int) -> None:
... print(f"epoch {epoch}")
...
>>> handler = EventHandler(epoch_handler, filter_payload=True)
>>> handler.handle(epoch=3, loss=0.5)
epoch 3
minevent.EventHandler.condition
property
¶
condition: Condition | None
Get the condition that controls handler execution.
Returns:
| Type | Description |
|---|---|
Condition | None
|
The condition that must evaluate to |
minevent.EventHandler.filter_payload
property
¶
filter_payload: bool
Indicate if the payload is filtered by the signature of the handler.
Returns:
| Type | Description |
|---|---|
bool
|
|
minevent.EventHandler.handler
property
¶
handler: Callable[..., object]
Get the handler function.
Returns:
| Type | Description |
|---|---|
Callable[..., object]
|
The handler function that will be called when the event is triggered. |
minevent.EventHandler.handler_args
property
¶
handler_args: tuple[Any, ...]
Get the positional arguments for the handler.
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
A tuple containing the positional arguments that will be passed to the handler when it is called. |
minevent.EventHandler.handler_kwargs
property
¶
handler_kwargs: dict[str, Any]
Get the keyword arguments for the handler.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A copy of the dictionary containing the keyword arguments that will be passed to the handler when it is called. Modifying the returned dictionary does not change the handler. |
minevent.EventHandler.ahandle
async
¶
ahandle(**payload: object) -> None
Handle the event asynchronously.
Like handle, but if the handler returns an awaitable (for
example because it is a coroutine function), the awaitable is
awaited. handle raises a TypeError for an awaitable, so
use ahandle (or EventManager.atrigger_event) with
coroutine functions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**payload
|
object
|
The keyword arguments given to
|
{}
|
Example
>>> import asyncio
>>> from minevent import EventHandler
>>> async def hello_handler() -> None:
... print("Hello!")
...
>>> asyncio.run(EventHandler(hello_handler).ahandle())
Hello!
minevent.EventHandler.handle ¶
handle(**payload: object) -> None
Handle the event.
Calls the handler if the condition is True (or if there is
no condition). The handler must be synchronous: a coroutine
function would be silently dropped, so it is rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**payload
|
object
|
The keyword arguments given to
|
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if the handler returns an awaitable. Use
|
Example
>>> from minevent import EventHandler
>>> async def hello_handler() -> None:
... print("Hello!")
...
>>> EventHandler(hello_handler).handle()
Traceback (most recent call last):
...
TypeError: ...hello_handler... returned an awaitable; use ahandle or atrigger_event
minevent.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.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.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 |
False
|
Returns:
| Type | Description |
|---|---|
Subscription
|
A subscription whose |
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
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.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 |
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.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 |
Example
>>> from minevent import EventHandler, EventManager
>>> manager = EventManager()
>>> _ = manager.add_event_handler("my_event", EventHandler(print))
>>> manager.clear_event("my_event")
>>> manager.events
[]
minevent.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
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
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.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 |
False
|
condition
|
Condition | None
|
An optional condition evaluated before the
handler. See |
None
|
filter_payload
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[_F], _F]
|
The decorator. |
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
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.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.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 |
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.PeriodicCondition ¶
Implement a periodic condition.
This condition evaluates to True on the first call and then every freq calls. It
maintains an internal counter that increments with each call. The condition is True when
the counter modulo freq equals zero.
Note that a call is not idempotent: each call advances the
counter, so the condition is stateful. Do not share one instance
between several handlers, because they would advance the same
counter. Use reset to restart the counter. The counter is not
protected by a lock, so a condition should be called from one
thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freq
|
int
|
The frequency (interval) at which the condition
evaluates to |
required |
skip_first
|
bool
|
If |
False
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
ValueError
|
if |
Example
>>> from minevent import PeriodicCondition
>>> condition = PeriodicCondition(freq=3)
>>> [condition() for _ in range(7)]
[True, False, False, True, False, False, True]
>>> condition = PeriodicCondition(freq=2, skip_first=True)
>>> [condition() for _ in range(3)]
[False, False, True]
minevent.PeriodicCondition.freq
property
¶
freq: int
Get the frequency of the periodic condition.
Returns:
| Type | Description |
|---|---|
int
|
The number of calls between each |
minevent.PeriodicCondition.skip_first
property
¶
skip_first: bool
Indicate if the first call is skipped.
Returns:
| Type | Description |
|---|---|
bool
|
|
minevent.PeriodicCondition.reset ¶
reset() -> None
Reset the internal counter, as if the condition was just created.
Example
>>> from minevent import PeriodicCondition
>>> condition = PeriodicCondition(freq=2)
>>> condition(), condition()
(True, False)
>>> condition.reset()
>>> condition()
True
minevent.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 |
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.Subscription.active
property
¶
active: bool
Indicate if the registration is still registered.
Returns:
| Type | Description |
|---|---|
bool
|
|
minevent.Subscription.event
property
¶
event: str
Get the event name of the registration.
Returns:
| Type | Description |
|---|---|
str
|
The event name. |
minevent.Subscription.event_handler
property
¶
event_handler: BaseEventHandler
minevent.Subscription.once
property
¶
once: bool
Indicate if the registration is removed before its first execution.
Returns:
| Type | Description |
|---|---|
bool
|
|
minevent.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
|
|