Main classes and functions¶
The names that minevent exports. Import them from the package, for example
from minevent import EventManager. To see how they work together, read
How It Works.
The package also exports __version__, the version of the installed package, as a str.
minevent ¶
Contain the main features of the minevent package.
minevent is a minimal event system with three concepts: an event (a
case-sensitive string), a handler (Handler) and an event manager
(EventManager) that registers the handlers and triggers the events.
A registration returns a Subscription, which removes it. Every
handler and condition receives the payload of a trigger in a read-only
Context, and a Condition, such as PeriodicCondition,
controls when a handler runs.
The package has no dependency, and __version__ is the version of the
installed package.
Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> _ = manager.add_event_handler("epoch_end", lambda context: print(f"epoch {context['epoch']}"))
>>> manager.trigger_event("epoch_end", {"epoch": 3})
epoch 3
minevent.Condition
module-attribute
¶
Condition = Callable[[Context], bool]
A condition: a function of the Context of the trigger that
returns a boolean.
minevent.Handler
module-attribute
¶
Handler = Callable[[Context], object]
A handler: a function of the Context of the trigger.
It can be synchronous or a coroutine function, which atrigger_event
awaits. A trigger ignores the value that it returns, unless it is
awaitable. The accepted signatures are the ones of
the calling rule.
minevent.Context ¶
Bases: Mapping[str, Any]
Implement a read-only mapping of the payload of a trigger.
The data is copied at construction into a private dict, whose keys
are checked, and a context has no method that changes it (no __setitem__,
update or pop), so neither the code that built the context
nor a handler can change what the next handler sees. The values
themselves are not copied: a mutable value stays mutable. A context
can be copied, deep-copied and pickled (with the protocol 2 or
higher, like the default one) if its values can.
The values are typed Any: a type checker lets a handler use a
value without a cast, and it does not check how the value is used.
context[key] reads a required value and raises a KeyError
if it is missing. Its message lists at most 20 of the keys and
shortens the long ones. context.get(key, default) reads an
optional value. get and key in context do not build the
message of that error, so they cost the same for a present key and a
missing one, whatever the number of keys. len, iteration, keys,
items, values and == behave like those of any
collections.abc.Mapping, so dict(context) is a valid
**kwargs. A context is equal to a mapping that has the same
items, and it is not hashable. The class is final: a type checker
reports a subclass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Mapping[str, object] | None
|
The mapping to copy, or |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
Example
>>> from minevent import Context
>>> context = Context({"epoch": 3, "loss": 0.5})
>>> context["epoch"]
3
>>> context.get("lr", 0.1)
0.1
>>> "loss" in context
True
>>> len(context)
2
>>> context
Context({'epoch': 3, 'loss': 0.5})
>>> import copy
>>> copy.deepcopy(context)
Context({'epoch': 3, 'loss': 0.5})
minevent.Context.get ¶
get(key: object, default: object = None) -> Any
Get an optional value.
Unlike context[key], a missing key costs the same as a
present one: no error message is built.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
object
|
The key to read. A key that is not a |
required |
default
|
object
|
The value returned if |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The value of |
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
Example
>>> from minevent import Context
>>> context = Context({"epoch": 3})
>>> context.get("epoch")
3
>>> context.get("lr", 0.1)
0.1
minevent.EventManager ¶
Implement an event manager.
add_event_handler registers a handler to an event, a
case-sensitive string, and returns the Subscription that removes
it. The on decorator registers the function that it decorates.
trigger_event and atrigger_event run the handlers of an event
in the order they were added, and clear_event and reset
remove registrations. events, get_subscriptions and
event in manager read the registry, which is thread-safe, and
repr shows the number of handlers of each event. A manager is
always truthy and has no length. Copying or pickling it raises a
TypeError. The guarantees and the limits are on the
How It Works
page of the documentation, and the reasons on the
Design Choices
page.
Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> _ = manager.add_event_handler("my_event", lambda _: print("Hello!"))
>>> manager.trigger_event("my_event")
Hello!
>>> manager
EventManager(events={'my_event': 1})
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. An event whose registrations were all removed counts as new when a handler is registered to it again. |
Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> manager.events
[]
>>> _ = manager.add_event_handler("my_event", lambda _: None)
>>> manager.events
['my_event']
>>> "my_event" in manager
True
minevent.EventManager.add_event_handler ¶
add_event_handler(
event: str,
handler: Handler,
*,
once: bool = False,
condition: Condition | None = None,
) -> Subscription
Add a handler to an event.
Each trigger of the event calls the handler after the handlers added
before it, as handler(context) with the read-only Context of
the trigger.
The calling rule
states which signatures are accepted. A coroutine function can be
registered too: atrigger_event awaits it, and trigger_event
rejects a trigger of its event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
str
|
The event name (case-sensitive string). |
required |
handler
|
Handler
|
The callable to attach to the event ( |
required |
once
|
bool
|
If |
False
|
condition
|
Condition | None
|
A synchronous function that returns a boolean, called
like a handler before it: the handler runs only if the result
is true. A stateful condition, such as |
None
|
Returns:
| Type | Description |
|---|---|
Subscription
|
A subscription whose |
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
Example
>>> from minevent import EventManager, PeriodicCondition
>>> manager = EventManager()
>>> _ = manager.add_event_handler(
... "epoch_end",
... lambda context: print(f"epoch {context['epoch']}"),
... condition=PeriodicCondition(freq=2),
... )
>>> _ = manager.add_event_handler("epoch_end", lambda _: print("first"), once=True)
>>> manager.trigger_event("epoch_end", {"epoch": 0})
epoch 0
first
>>> manager.trigger_event("epoch_end", {"epoch": 1})
>>> manager.trigger_event("epoch_end", {"epoch": 2})
epoch 2
minevent.EventManager.atrigger_event
async
¶
atrigger_event(
event: str, context: Mapping[str, object] | None = None
) -> None
Run the handlers of an event, awaiting the coroutine handlers.
It behaves like trigger_event, but the awaitable that a handler
returns is awaited before the next handler. A synchronous handler
blocks the event loop while it runs. The registrations and the context
are read when the coroutine starts to run, not when it is created
(see the
limits).
Both arguments are positional-only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
str
|
The event name (case-sensitive string) to trigger. |
required |
context
|
Mapping[str, object] | None
|
The data of the trigger, as in |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
RuntimeError
|
if a handler or a condition raises a
|
Example
>>> import asyncio
>>> from minevent import EventManager
>>> manager = EventManager()
>>> async def hello_handler(context):
... print(f"Hello {context['name']}!")
...
>>> _ = manager.add_event_handler("my_event", 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 registrations of an event.
Nothing happens if the event has no handler. The removed handlers are released outside the lock, so their finalizers can use the manager.
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 EventManager
>>> manager = EventManager()
>>> _ = manager.add_event_handler("my_event", lambda _: None)
>>> 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 EventManager
>>> manager = EventManager()
>>> manager.get_subscriptions("my_event")
()
>>> def handler(_):
... print("Hello!")
...
>>> subscription = manager.add_event_handler("my_event", handler)
>>> manager.get_subscriptions("my_event") == (subscription,)
True
>>> subscription.handler is handler
True
>>> len(manager.get_subscriptions("my_event"))
1
minevent.EventManager.on ¶
on(
event: str,
*,
once: bool = False,
condition: Condition | None = None,
) -> Callable[[_F], _F]
Create a decorator that registers a function as a handler.
The decorated function is registered with
add_event_handler(event, func, once=once, condition=condition)
and returned unchanged. Use add_event_handler if you need the
Subscription.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
str
|
The event name (case-sensitive string). |
required |
once
|
bool
|
See |
False
|
condition
|
Condition | None
|
See |
None
|
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(context):
... print(f"Hello {context['name']}!")
...
>>> manager.trigger_event("my_event", {"name": "Bob"})
Hello Bob!
>>> hello_handler({"name": "Alice"})
Hello Alice!
minevent.EventManager.reset ¶
reset() -> None
Remove all the registrations of all the events.
The removed handlers are released outside the lock, so their finalizers can use the manager.
Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> _ = manager.add_event_handler("my_event", lambda _: None)
>>> manager.reset()
>>> manager
EventManager(events={})
minevent.EventManager.trigger_event ¶
trigger_event(
event: str, context: Mapping[str, object] | None = None
) -> None
Run the handlers of an event, in the order they were added.
The handlers registered when the trigger starts run one after the
other, and a registration removed before its handler is called, even
by its own condition, does not run. The condition of a registration is
evaluated just before its handler.
No handler runs if the event has none. The trigger is fail-fast:
an exception of a handler or a condition propagates unwrapped, with a
note that says what raised it, and the next handlers are skipped.
If one of the registrations has a coroutine function as handler (a
callable object is judged by its __call__), the trigger is
rejected before any condition or handler runs. Both arguments are
positional-only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
str
|
The event name (case-sensitive string) to trigger. |
required |
context
|
Mapping[str, object] | None
|
The data of the trigger: a mapping from |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> manager.trigger_event("epoch_end") # no handler: nothing happens
>>> _ = manager.add_event_handler(
... "epoch_end", lambda context: print(f"epoch {context['epoch']}")
... )
>>> manager.trigger_event("epoch_end", {"epoch": 3})
epoch 3
minevent.PeriodicCondition ¶
Implement a periodic condition.
This condition evaluates to True on one call in freq, from the call of index
start (the first call has the index 0). It maintains an internal counter that increments
with each call. The condition is True when the counter minus start is not negative and
is a multiple of freq. With freq=3, start=0 is True on the calls 0, 3 and 6,
start=3 skips the first call (3, 6 and 9), and start=2 is True at the end of every
third call (2, 5 and 8). With freq=1, it is a warm-up: False for the first start
calls and True afterwards.
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. The step property reads the counter without advancing
it, and reset restarts it. The condition is called with the
context of the trigger, like any condition, and ignores it.
The counter is protected by a lock, so every call is counted once,
from any number of threads, with and without the GIL. A lock cannot
be copied or pickled: a copy of a condition (copy.copy,
copy.deepcopy or pickle) starts at the same step, and then
has its own counter and lock. Its repr shows freq, start
and step as Python writes integers, without separator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freq
|
int
|
The frequency (interval) at which the condition
evaluates to |
required |
start
|
int
|
The index, from 0, of the first call that evaluates to
|
0
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
ValueError
|
if |
Example
>>> from minevent import Context, PeriodicCondition
>>> context = Context()
>>> condition = PeriodicCondition(freq=3)
>>> [condition(context) for _ in range(7)]
[True, False, False, True, False, False, True]
>>> condition = PeriodicCondition(freq=3, start=2)
>>> [condition(context) for _ in range(7)]
[False, False, True, False, False, True, False]
>>> condition = PeriodicCondition(freq=1, start=2)
>>> [condition(context) for _ in range(4)]
[False, False, True, True]
>>> import copy
>>> clone = copy.deepcopy(condition)
>>> clone
PeriodicCondition(freq=1, start=2, step=4)
minevent.PeriodicCondition.freq
property
¶
freq: int
Get the frequency of the periodic condition.
Returns:
| Type | Description |
|---|---|
int
|
The period of the condition: from the call of index
|
Example
>>> from minevent import PeriodicCondition
>>> PeriodicCondition(freq=3).freq
3
minevent.PeriodicCondition.start
property
¶
start: int
Get the index of the first call that is True.
Returns:
| Type | Description |
|---|---|
int
|
The index, from 0, of the first call that evaluates to
|
Example
>>> from minevent import PeriodicCondition
>>> PeriodicCondition(freq=3, start=2).start
2
minevent.PeriodicCondition.step
property
¶
step: int
Get the number of calls counted by the condition.
Reading it does not advance the counter.
Returns:
| Type | Description |
|---|---|
int
|
The number of calls since the creation or the last
|
Example
>>> from minevent import Context, PeriodicCondition
>>> condition = PeriodicCondition(freq=3)
>>> condition.step
0
>>> condition(Context()), condition(Context())
(True, False)
>>> condition.step
2
minevent.PeriodicCondition.reset ¶
reset() -> None
Reset the internal counter, as if the condition was just created.
Example
>>> from minevent import Context, PeriodicCondition
>>> condition = PeriodicCondition(freq=2)
>>> condition(Context()), condition(Context())
(True, False)
>>> condition.reset()
>>> condition(Context())
True
minevent.Subscription ¶
Represent the registration of a handler to an event.
EventManager.add_event_handler returns a subscription: it is the
registration itself, so remove removes that registration only,
even if the same handler is registered several times. Subscriptions
are compared by identity, and copying or pickling one raises a
TypeError. A subscription is a context manager: the
registration is removed when the with block exits. Its repr
shows the event and the name of the handler, then what else decides
whether the handler runs: once=True, the name of the condition
and active=False if the registration is not in the manager.
The constructor is internal: subscriptions are created by the event
manager, and one that is built by hand is not active.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manager
|
EventManager
|
The event manager that stores the registration. |
required |
event
|
str
|
The event name of the registration. |
required |
handler
|
Handler
|
The registered handler ( |
required |
once
|
bool
|
If |
False
|
condition
|
Condition | None
|
The condition evaluated before the handler, or
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
Example
>>> from minevent import EventManager
>>> def print_epoch(context):
... print(context["epoch"])
...
>>> def is_late(context):
... return context["epoch"] >= 2
...
>>> manager = EventManager()
>>> subscription = manager.add_event_handler("my_event", lambda _: None)
>>> subscription
Subscription(event='my_event', handler='<lambda>')
>>> subscription.remove(), subscription.remove()
(True, False)
>>> subscription.active
False
>>> subscription
Subscription(event='my_event', handler='<lambda>', active=False)
>>> manager.add_event_handler("my_event", print_epoch, once=True, condition=is_late)
Subscription(event='my_event', handler='print_epoch', once=True, condition='is_late')
>>> manager.reset()
>>> with manager.add_event_handler("my_event", lambda _: None):
... manager
...
EventManager(events={'my_event': 1})
>>> manager
EventManager(events={})
minevent.Subscription.active
property
¶
active: bool
Indicate if the registration is still registered.
Returns:
| Type | Description |
|---|---|
bool
|
|
Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> subscription = manager.add_event_handler("epoch_end", lambda _: None)
>>> subscription.active
True
>>> manager.reset()
>>> subscription.active
False
minevent.Subscription.condition
property
¶
condition: Condition | None
Get the condition evaluated before the handler.
Returns:
| Type | Description |
|---|---|
Condition | None
|
The condition, or |
Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> print(manager.add_event_handler("epoch_end", lambda _: None).condition)
None
minevent.Subscription.event
property
¶
event: str
Get the event name of the registration.
Returns:
| Type | Description |
|---|---|
str
|
The event name. |
Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> manager.add_event_handler("epoch_end", lambda _: None).event
'epoch_end'
minevent.Subscription.handler
property
¶
handler: Handler
Get the registered handler.
Returns:
| Type | Description |
|---|---|
Handler
|
The handler given to |
Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> def handler(_) -> None: ...
>>> manager.add_event_handler("epoch_end", handler).handler is handler
True
minevent.Subscription.once
property
¶
once: bool
Indicate if the registration is removed just before its first execution.
Returns:
| Type | Description |
|---|---|
bool
|
|
Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> manager.add_event_handler("epoch_end", lambda _: None, once=True).once
True
minevent.Subscription.remove ¶
remove() -> bool
Remove this registration.
Removing a registration that is already removed is not an error, and the cost does not depend on the number of handlers of the event.
Returns:
| Type | Description |
|---|---|
bool
|
|
Example
>>> from minevent import EventManager
>>> manager = EventManager()
>>> subscription = manager.add_event_handler("epoch_end", lambda _: None)
>>> subscription.remove()
True
>>> subscription.remove()
False