Examples¶
This page shows how to use minevent in practical situations. The pycon examples run as written.
The quickstart shows each feature on its own, the user guide lists the
recommendations and the how it works page states the rules.
Training loops¶
Add behavior to a loop that triggers events.
Add logging to a training loop¶
The training loop triggers events and knows nothing about the handlers. The caller decides what happens, so logging, checkpointing or monitoring is added without changing the loop:
>>> from minevent import EventManager
>>> def train(manager: EventManager, epochs: int) -> None:
... manager.trigger_event("training_start")
... for epoch in range(epochs):
... loss = 1.0 / (epoch + 1)
... manager.trigger_event("epoch_end", {"epoch": epoch, "loss": loss})
... manager.trigger_event("training_end")
>>> manager = EventManager()
>>> train(manager, epochs=2)
>>> _ = manager.add_event_handler("training_start", lambda _: print("Training started"))
>>> _ = manager.add_event_handler(
... "epoch_end", lambda context: print(f"epoch {context['epoch']}: loss={context['loss']}")
... )
>>> _ = manager.add_event_handler("training_end", lambda _: print("Training ended"))
>>> train(manager, epochs=2)
Training started
epoch 0: loss=1.0
epoch 1: loss=0.5
Training ended
The first call of train prints nothing because no handler is registered.
Run a handler every N epochs¶
Give the registration a condition. PeriodicCondition(freq=3) is True on the first call and then
every three calls. start is the index (from 0) of the first call that is True: start=3 skips
the first call:
>>> from minevent import EventManager, PeriodicCondition
>>> manager = EventManager()
>>> _ = manager.add_event_handler(
... "epoch_end",
... lambda context: print(f"checkpoint at epoch {context['epoch']}"),
... condition=PeriodicCondition(freq=3, start=3),
... )
>>> for epoch in range(7):
... manager.trigger_event("epoch_end", {"epoch": epoch})
checkpoint at epoch 3
checkpoint at epoch 6
With the epochs counted from 0, start=2 runs the handler at the end of every third epoch:
>>> from minevent import EventManager, PeriodicCondition
>>> manager = EventManager()
>>> _ = manager.add_event_handler(
... "epoch_end",
... lambda context: print(f"evaluate at epoch {context['epoch']}"),
... condition=PeriodicCondition(freq=3, start=2),
... )
>>> for epoch in range(7):
... manager.trigger_event("epoch_end", {"epoch": epoch})
evaluate at epoch 2
evaluate at epoch 5
With freq=1, the condition is False for the first start calls, then always True, which is
useful for a warm-up:
>>> from minevent import EventManager, PeriodicCondition
>>> manager = EventManager()
>>> _ = manager.add_event_handler(
... "epoch_end",
... lambda context: print(f"validate at epoch {context['epoch']}"),
... condition=PeriodicCondition(freq=1, start=2),
... )
>>> for epoch in range(4):
... manager.trigger_event("epoch_end", {"epoch": epoch})
validate at epoch 2
validate at epoch 3
Resume a training¶
A PeriodicCondition counts its calls: a new one, in a training resumed at epoch 7, counts from 0
and not from the epoch. If the payload has the epoch, decide from it:
>>> from minevent import EventManager
>>> manager = EventManager()
>>> _ = manager.add_event_handler(
... "epoch_end",
... lambda context: print(f"checkpoint at epoch {context['epoch']}"),
... condition=lambda context: context["epoch"] % 3 == 0,
... )
>>> for epoch in range(7, 13): # resumed at epoch 7
... manager.trigger_event("epoch_end", {"epoch": epoch})
checkpoint at epoch 9
checkpoint at epoch 12
Otherwise, save the condition with the checkpoint: it can be pickled, and the copy continues from the same count. Load a pickle from a source that you trust only.
>>> import pickle
>>> from minevent import Context, EventManager, PeriodicCondition
>>> def save(context: Context) -> None:
... print(f"checkpoint at epoch {context['epoch']}")
>>> condition = PeriodicCondition(freq=3)
>>> manager = EventManager()
>>> _ = manager.add_event_handler("epoch_end", save, condition=condition)
>>> for epoch in range(7):
... manager.trigger_event("epoch_end", {"epoch": epoch})
checkpoint at epoch 0
checkpoint at epoch 3
checkpoint at epoch 6
>>> state = pickle.dumps(condition) # saved with the model
>>> manager = EventManager() # the resumed training
>>> _ = manager.add_event_handler("epoch_end", save, condition=pickle.loads(state))
>>> for epoch in range(7, 13):
... manager.trigger_event("epoch_end", {"epoch": epoch})
checkpoint at epoch 9
checkpoint at epoch 12
Stop a training early¶
A trigger returns nothing, so a handler answers the loop through an object that both can read. Here the handler keeps a flag, and the loop reads it after the trigger:
>>> from minevent import Context, EventManager
>>> class EarlyStopping:
... def __init__(self, patience: int) -> None:
... self.patience = patience
... self.best = float("inf")
... self.bad_epochs = 0
...
... def __call__(self, context: Context) -> None:
... if context["loss"] < self.best:
... self.best, self.bad_epochs = context["loss"], 0
... else:
... self.bad_epochs += 1
...
... @property
... def should_stop(self) -> bool:
... return self.bad_epochs >= self.patience
>>> manager = EventManager()
>>> stopping = EarlyStopping(patience=2)
>>> _ = manager.add_event_handler("epoch_end", stopping)
>>> for epoch, loss in enumerate([0.9, 0.6, 0.7, 0.8, 0.5]):
... manager.trigger_event("epoch_end", {"epoch": epoch, "loss": loss})
... if stopping.should_stop:
... print(f"stop after epoch {epoch}")
... break
stop after epoch 3
Time each epoch¶
An object can register several of its methods, which share its state. The clock is an argument, so the example (and a test) can give a fake one:
>>> import time
>>> from collections.abc import Callable
>>> from minevent import Context, EventManager
>>> class EpochTimer:
... def __init__(self, clock: Callable[[], float] = time.perf_counter) -> None:
... self.clock = clock
... self.durations = []
...
... def start(self, _: Context) -> None:
... self.started = self.clock()
...
... def stop(self, _: Context) -> None:
... self.durations.append(self.clock() - self.started)
>>> timer = EpochTimer(clock=iter([0.0, 2.0, 10.0, 13.0]).__next__)
>>> manager = EventManager()
>>> _ = manager.add_event_handler("epoch_start", timer.start)
>>> _ = manager.add_event_handler("epoch_end", timer.stop)
>>> for _ in range(2):
... manager.trigger_event("epoch_start")
... manager.trigger_event("epoch_end")
>>> timer.durations
[2.0, 3.0]
The duration includes the handlers of epoch_start registered after timer.start, and the ones of
epoch_end registered before timer.stop.
Trigger an event from a handler¶
A handler can trigger another event of the same manager, for example to announce what it found. The new event runs completely before the next handler of the first one:
>>> from minevent import Context, EventManager
>>> manager = EventManager()
>>> best = [float("inf")]
>>> def track_best(context: Context) -> None:
... if context["loss"] < best[0]:
... best[0] = context["loss"]
... manager.trigger_event("new_best", context)
>>> _ = manager.add_event_handler("epoch_end", track_best)
>>> _ = manager.add_event_handler("epoch_end", lambda context: print(f"end {context['epoch']}"))
>>> _ = manager.add_event_handler(
... "new_best", lambda context: print(f"save the model of epoch {context['epoch']}")
... )
>>> for epoch, loss in enumerate([0.9, 0.4, 0.6]):
... manager.trigger_event("epoch_end", {"epoch": epoch, "loss": loss})
save the model of epoch 0
end 0
save the model of epoch 1
end 1
end 2
A handler that triggers its own event recurses (see the limits).
Conditions¶
Decide when a handler runs.
Write a custom condition¶
A class with __call__ is useful when a condition has a state or reads another object:
>>> from minevent import Context, EventManager
>>> class Flag:
... def __init__(self) -> None:
... self.enabled = False
...
... def __call__(self, _: Context) -> bool:
... return self.enabled
>>> verbose = Flag()
>>> manager = EventManager()
>>> _ = manager.add_event_handler("batch_end", lambda _: print("batch done"), condition=verbose)
>>> manager.trigger_event("batch_end")
>>> verbose.enabled = True
>>> manager.trigger_event("batch_end")
batch done
Decide from the payload¶
A condition reads the payload of the trigger. A handler and its condition can read different keys:
>>> from minevent import Context, EventManager
>>> def is_improving(context: Context) -> bool:
... return context.get("loss", 1.0) < 0.5
>>> manager = EventManager()
>>> _ = manager.add_event_handler(
... "epoch_end",
... lambda context: print(f"save the model of epoch {context['epoch']}"),
... condition=is_improving,
... )
>>> for epoch, loss in enumerate([0.9, 0.4, 0.6, 0.3]):
... manager.trigger_event("epoch_end", {"epoch": epoch, "loss": loss})
save the model of epoch 1
save the model of epoch 3
PeriodicCondition ignores the payload. To combine it with a condition on the payload, write a
function that calls both:
condition=lambda context: periodic(context) and is_improving(context).
Combine conditions¶
Write a function. all([a(context), b(context)]) evaluates every condition at each call, so
stateful conditions advance together:
>>> from minevent import EventManager, PeriodicCondition
>>> after_one, periodic = PeriodicCondition(freq=1, start=1), PeriodicCondition(freq=2)
>>> manager = EventManager()
>>> _ = manager.add_event_handler(
... "epoch_end",
... lambda _: print("validate"),
... condition=lambda context: all([after_one(context), periodic(context)]),
... )
>>> for _ in range(5):
... manager.trigger_event("epoch_end")
validate
validate
Use one condition per handler¶
A stateful condition keeps its counter in the instance, so create one per registration, for example with a function:
>>> import functools
>>> from minevent import Context, EventManager, PeriodicCondition
>>> manager = EventManager()
>>> def say(name: str, _: Context) -> None:
... print(name)
>>> def register(name: str) -> None:
... manager.add_event_handler(
... name, functools.partial(say, name), condition=PeriodicCondition(freq=2)
... )
>>> register("first")
>>> register("second")
>>> manager.trigger_event("first")
first
>>> manager.trigger_event("second")
second
Restart a condition¶
reset() restarts the counter of a PeriodicCondition, for example at the start of a new training:
>>> from minevent import EventManager, PeriodicCondition
>>> warmup = PeriodicCondition(freq=1, start=1)
>>> manager = EventManager()
>>> _ = manager.add_event_handler("epoch_end", lambda _: print("validate"), condition=warmup)
>>> for _ in range(2):
... manager.trigger_event("epoch_end")
validate
>>> warmup.reset()
>>> manager.trigger_event("epoch_end")
Handlers and payload¶
Write, adapt and organize the handlers.
Adapt an existing function¶
A handler is called with the context, so wrap a function that does not take it, such as
model.train, in a lambda that ignores it and chooses the arguments. A default saves the value of a
loop variable:
>>> from minevent import EventManager
>>> class Model:
... def train(self, mode: bool = True) -> None:
... print(f"train mode: {mode}")
>>> model = Model()
>>> manager = EventManager()
>>> _ = manager.add_event_handler("epoch_start", lambda _: model.train())
>>> _ = manager.add_event_handler("validation_start", lambda _: model.train(mode=False))
>>> manager.trigger_event("epoch_start", {"epoch": 0})
train mode: True
>>> manager.trigger_event("validation_start")
train mode: False
>>> for i in range(3):
... _ = manager.add_event_handler("batch_end", lambda _, i=i: print(i))
>>> manager.trigger_event("batch_end")
0
1
2
Forward the payload to a function¶
A Context is a mapping, so **context passes its keys as keyword arguments. The function must
accept every key of the payload, here with **metrics:
>>> from minevent import EventManager
>>> def report(**metrics: float) -> None:
... print(", ".join(f"{name}={value}" for name, value in metrics.items()))
>>> manager = EventManager()
>>> _ = manager.add_event_handler("epoch_end", lambda context: report(**context))
>>> manager.trigger_event("epoch_end", {"loss": 0.5, "accuracy": 0.8})
loss=0.5, accuracy=0.8
Keep a state in a handler¶
A class with a __call__(self, context) method is a handler with its own state. This one
collects the losses and is read after the training:
>>> from minevent import Context, EventManager
>>> class LossHistory:
... def __init__(self) -> None:
... self.losses = []
...
... def __call__(self, context: Context) -> None:
... self.losses.append(context["loss"])
>>> history = LossHistory()
>>> manager = EventManager()
>>> _ = manager.add_event_handler("epoch_end", history)
>>> for epoch, loss in enumerate([0.9, 0.6, 0.4]):
... manager.trigger_event("epoch_end", {"epoch": epoch, "loss": loss})
>>> history.losses
[0.9, 0.6, 0.4]
The handler ignores the keys that it does not read, here epoch.
Pass a dict or a Context¶
A dict is copied and validated at each trigger, while a Context is passed as is, so build it once
to reuse it:
>>> from minevent import Context, EventManager
>>> manager = EventManager()
>>> _ = manager.add_event_handler(
... "epoch_end", lambda context: print(f"epoch {context['epoch']}, loss {context['loss']}")
... )
>>> manager.trigger_event("epoch_end", {"epoch": 3, "loss": 0.5})
epoch 3, loss 0.5
>>> context = Context({"epoch": 4, "loss": 0.4})
>>> manager.trigger_event("epoch_end", context)
epoch 4, loss 0.4
>>> manager.trigger_event("epoch_end", context)
epoch 4, loss 0.4
Keep a snapshot of the payload¶
The values of a Context are not copied. copy.deepcopy takes a snapshot that the next handlers
cannot change:
>>> import copy
>>> from minevent import EventManager
>>> snapshots = []
>>> manager = EventManager()
>>> _ = manager.add_event_handler("epoch_end", lambda context: snapshots.append(copy.deepcopy(context)))
>>> _ = manager.add_event_handler("epoch_end", lambda context: context["losses"].append(0.1))
>>> manager.trigger_event("epoch_end", {"losses": [0.5]})
>>> snapshots
[Context({'losses': [0.5]})]
Name the events in one place¶
A typo in an event name is silent. A StrEnum member is a str, so it can be used as an event, and
a typo in the name of a member raises an AttributeError:
>>> from enum import StrEnum
>>> from minevent import EventManager
>>> class Event(StrEnum):
... EPOCH_START = "epoch_start"
... EPOCH_END = "epoch_end"
>>> manager = EventManager()
>>> _ = manager.add_event_handler(Event.EPOCH_END, lambda _: print("epoch done"))
>>> manager.trigger_event(Event.EPOCH_END)
epoch done
>>> manager.trigger_event("epoch_end") # the same event
epoch done
Register a handler to several events¶
Register it once per event. The payload does not say which event was triggered, so bind the name
with functools.partial if the handler needs it:
>>> import functools
>>> from minevent import Context, EventManager
>>> def log(event: str, context: Context) -> None:
... print(f"{event}: {dict(context)}")
>>> manager = EventManager()
>>> for event in ["epoch_end", "training_end"]:
... _ = manager.add_event_handler(event, functools.partial(log, event))
>>> manager.trigger_event("epoch_end", {"epoch": 0})
epoch_end: {'epoch': 0}
>>> manager.trigger_event("training_end")
training_end: {}
Register handlers for a part of the program¶
A Subscription is a context manager: its registration is removed when the with block exits, also
when the block raises. One with statement can hold several of them:
>>> from minevent import EventManager
>>> manager = EventManager()
>>> with (
... manager.add_event_handler("batch_start", lambda _: print("start the profiler")),
... manager.add_event_handler("batch_end", lambda _: print("stop the profiler")),
... ):
... manager.trigger_event("batch_start")
... manager.trigger_event("batch_end")
... raise RuntimeError("out of memory")
Traceback (most recent call last):
...
RuntimeError: out of memory
>>> manager
EventManager(events={})
Remove a handler after it succeeds¶
once=True removes a registration before the call, so a handler that fails is not tried again. To
retry until a success, register without once and remove the Subscription in the handler:
>>> from minevent import Context, EventManager
>>> class Upload:
... def __init__(self, manager: EventManager) -> None:
... self.subscription = manager.add_event_handler("epoch_end", self)
...
... def __call__(self, context: Context) -> None:
... if not context["online"]:
... print("offline, retry at the next epoch")
... return
... print("uploaded")
... self.subscription.remove()
>>> manager = EventManager()
>>> upload = Upload(manager)
>>> for online in [False, True, True]:
... manager.trigger_event("epoch_end", {"online": online})
offline, retry at the next epoch
uploaded
Continue after a handler fails¶
A trigger stops at the first error. If the failure of a handler must not stop the next ones, catch its exceptions in a wrapper, and report them:
>>> import functools
>>> from minevent import Context, EventManager
>>> def optional(handler):
... @functools.wraps(handler)
... def wrapper(context):
... try:
... handler(context)
... except OSError as exc:
... print(f"{handler.__name__} failed: {exc}")
...
... return wrapper
>>> def send_report(_: Context) -> None:
... raise ConnectionError("no network")
>>> manager = EventManager()
>>> _ = manager.add_event_handler("training_end", optional(send_report))
>>> _ = manager.add_event_handler("training_end", lambda _: print("save the model"))
>>> manager.trigger_event("training_end")
send_report failed: no network
save the model
Catch the exceptions that you expect only, so a mistake in the handler still reaches the caller.
A real program writes them to its log. This wrapper is for synchronous handlers: a coroutine function
needs an async def wrapper that awaits it.
Register a handler only once¶
Registering the same handler twice runs it twice. Look at the registrations to add it only if it is
not there. Compare with ==, not is: a bound method such as greeter.hello is a new object at
each access.
>>> from minevent import Context, EventManager
>>> class Greeter:
... def hello(self, _: Context) -> None:
... print("Hello!")
>>> greeter = Greeter()
>>> manager = EventManager()
>>> for _ in range(3):
... if not any(s.handler == greeter.hello for s in manager.get_subscriptions("my_event")):
... _ = manager.add_event_handler("my_event", greeter.hello)
>>> manager
EventManager(events={'my_event': 1})
Write a plugin¶
A plugin registers its handlers when it is set up, and keeps the subscriptions to remove them when it is torn down:
>>> from minevent import Context, EventManager
>>> class ProgressPlugin:
... def setup(self, manager: EventManager) -> None:
... self.subscriptions = [
... manager.add_event_handler("epoch_start", self.on_epoch_start),
... manager.add_event_handler("epoch_end", self.on_epoch_end),
... ]
...
... def teardown(self) -> None:
... for subscription in self.subscriptions:
... subscription.remove()
...
... def on_epoch_start(self, context: Context) -> None:
... print(f"start {context['epoch']}")
...
... def on_epoch_end(self, context: Context) -> None:
... print(f"end {context['epoch']}")
>>> manager = EventManager()
>>> plugin = ProgressPlugin()
>>> plugin.setup(manager)
>>> manager.trigger_event("epoch_start", {"epoch": 0})
start 0
>>> manager.trigger_event("epoch_end", {"epoch": 0})
end 0
>>> plugin.teardown()
>>> manager
EventManager(events={})
Copy an object that holds a manager¶
A manager and a subscription cannot be copied or pickled. An object that holds one defines what its copy keeps, here everything except the manager, which is replaced by an empty one:
>>> import copy
>>> from minevent import EventManager
>>> class Trainer:
... def __init__(self) -> None:
... self.epoch = 0
... self.manager = EventManager()
...
... def __getstate__(self) -> dict:
... return {key: value for key, value in self.__dict__.items() if key != "manager"}
...
... def __setstate__(self, state: dict) -> None:
... self.__dict__.update(state)
... self.manager = EventManager()
>>> trainer = Trainer()
>>> trainer.epoch = 3
>>> _ = trainer.manager.add_event_handler("epoch_end", lambda _: None)
>>> clone = copy.deepcopy(trainer) # pickle uses the same methods
>>> clone.epoch
3
>>> clone.manager
EventManager(events={})
The copy has no handler: register them again, for example with a plugin.
Trace the handlers¶
Wrap a handler to see its calls. functools.wraps keeps the signature, which is checked at
registration:
>>> import functools
>>> from minevent import Context, EventManager
>>> def traced(handler):
... @functools.wraps(handler)
... def wrapper(*args):
... print(f"calling {handler.__name__}")
... return handler(*args)
...
... return wrapper
>>> def log_epoch(context: Context) -> None:
... print(f"epoch {context['epoch']}")
>>> manager = EventManager()
>>> _ = manager.add_event_handler("epoch_end", traced(log_epoch))
>>> _ = manager.add_event_handler("epoch_end", lambda context: print(dict(context)))
>>> manager.trigger_event("epoch_end", {"epoch": 1})
calling log_epoch
epoch 1
{'epoch': 1}
Threads and async¶
Use the manager in concurrent programs.
Trigger events from several threads¶
The manager can be shared between threads. The handlers run in the thread that triggers the event, possibly at the same time, so a handler protects the state that it shares:
>>> import threading
>>> from minevent import Context, EventManager
>>> total, lock = [0], threading.Lock()
>>> def add(context: Context) -> None:
... with lock:
... total[0] += context["value"]
>>> manager = EventManager()
>>> _ = manager.add_event_handler("item_done", add)
>>> threads = [
... threading.Thread(target=manager.trigger_event, args=("item_done", {"value": i}))
... for i in range(10)
... ]
>>> for thread in threads:
... thread.start()
>>> for thread in threads:
... thread.join()
>>> total
[45]
Trigger events from an async function¶
In an async program, await the trigger inside your coroutines. The next step starts when every
handler is done:
>>> import asyncio
>>> from minevent import Context, EventManager
>>> async def fetch_all(manager: EventManager, urls: list[str]) -> None:
... await manager.atrigger_event("fetch_start", {"count": len(urls)})
... for url in urls:
... await asyncio.sleep(0) # a real program awaits a request here
... await manager.atrigger_event("fetch_done", {"url": url})
... await manager.atrigger_event("fetch_end")
>>> async def log_done(context: Context) -> None:
... print(f"fetched {context['url']}")
>>> manager = EventManager()
>>> _ = manager.add_event_handler(
... "fetch_start", lambda context: print(f"fetching {context['count']} urls")
... )
>>> _ = manager.add_event_handler("fetch_done", log_done)
>>> _ = manager.add_event_handler("fetch_end", lambda _: print("done"))
>>> asyncio.run(fetch_all(manager, ["a.com", "b.com"]))
fetching 2 urls
fetched a.com
fetched b.com
done
Use options with coroutine handlers¶
once, condition and the on decorator work the same way with coroutine
handlers:
>>> import asyncio
>>> from minevent import Context, EventManager, PeriodicCondition
>>> manager = EventManager()
>>> @manager.on("epoch_end", condition=PeriodicCondition(freq=2))
... async def upload(context: Context) -> None:
... await asyncio.sleep(0)
... print(f"uploaded epoch {context['epoch']}")
>>> async def main() -> None:
... for epoch in range(3):
... await manager.atrigger_event("epoch_end", {"epoch": epoch, "loss": 0.5})
>>> asyncio.run(main())
uploaded epoch 0
uploaded epoch 2
Run the work of a handler concurrently¶
The handlers of an event run sequentially, so a slow handler delays the next ones. To run several
awaitables at the same time, use asyncio.gather inside one handler:
>>> import asyncio
>>> from minevent import Context, EventManager
>>> async def upload(name: str) -> str:
... await asyncio.sleep(0)
... return name
>>> async def upload_all(context: Context) -> None:
... done = await asyncio.gather(*(upload(name) for name in context["files"]))
... print(f"uploaded {done}")
>>> manager = EventManager()
>>> _ = manager.add_event_handler("training_end", upload_all)
>>> asyncio.run(manager.atrigger_event("training_end", {"files": ["a.pt", "b.pt"]}))
uploaded ['a.pt', 'b.pt']
Hand a long computation to an executor (await loop.run_in_executor(...) or asyncio.to_thread)
from a coroutine handler.
Start background work from a handler¶
A handler that starts background work returns nothing. A task is awaitable, so a handler such as
lambda _: loop.create_task(upload()) returns one: trigger_event raises after the task is
scheduled, and atrigger_event waits for it. Start the task in a function that returns None:
>>> import asyncio
>>> from minevent import Context, EventManager
>>> async def upload(path: str) -> None:
... await asyncio.sleep(0)
... print(f"uploaded {path}")
>>> tasks = set() # asyncio keeps a weak reference to a task only
>>> def start_upload(context: Context) -> None:
... task = asyncio.get_running_loop().create_task(upload(context["path"]))
... tasks.add(task)
... task.add_done_callback(tasks.discard)
>>> manager = EventManager()
>>> _ = manager.add_event_handler("checkpoint_saved", start_upload)
>>> async def main() -> None:
... manager.trigger_event("checkpoint_saved", {"path": "model.pt"})
... print("training continues")
... await asyncio.gather(*tasks)
>>> asyncio.run(main())
training continues
uploaded model.pt
The task needs a running event loop, so the event is triggered from a coroutine. The manager does not see the task: await it before the loop ends, and handle its errors in the coroutine that it runs.
Tests¶
Check your handlers and their registration.
Test a handler¶
A handler is a plain callable, so test it without a manager. Test the wiring with a mock:
from unittest.mock import create_autospec
from minevent import Context, EventManager
def log_epoch(context: Context) -> None:
print(f"epoch {context['epoch']}")
def test_epoch_end_calls_the_handler():
manager = EventManager()
handler = create_autospec(log_epoch) # a mock with the signature of log_epoch
manager.add_event_handler("epoch_end", handler)
manager.trigger_event("epoch_end", {"epoch": 1})
handler.assert_called_once_with({"epoch": 1})
An async handler is tested with asyncio.run (or the async support of your test framework):
import asyncio
from unittest.mock import create_autospec
from minevent import Context, EventManager
async def upload(context: Context) -> None:
await asyncio.sleep(0)
def test_epoch_end_awaits_the_handler():
manager = EventManager()
handler = create_autospec(upload) # an async mock with the signature of upload
manager.add_event_handler("epoch_end", handler)
asyncio.run(manager.atrigger_event("epoch_end", {"epoch": 1}))
handler.assert_awaited_once_with({"epoch": 1})
Test the events that your code triggers¶
Register a mock to the event, run your code and check the payloads:
from unittest.mock import call, create_autospec
from minevent import Context, EventManager
def train(manager: EventManager, epochs: int) -> None:
for epoch in range(epochs):
manager.trigger_event("epoch_end", {"epoch": epoch})
def record(context: Context) -> None:
pass
def test_train_triggers_epoch_end_at_each_epoch():
manager = EventManager()
handler = create_autospec(record)
manager.add_event_handler("epoch_end", handler)
train(manager, epochs=2)
assert handler.call_args_list == [call({"epoch": 0}), call({"epoch": 1})]
Test a condition¶
A condition is a plain function too: call it with a Context.
from minevent import Context
def is_improving(context: Context) -> bool:
return context.get("loss", 1.0) < 0.5
def test_is_improving_low_loss():
assert is_improving(Context({"loss": 0.4}))
def test_is_improving_missing_loss():
assert not is_improving(Context())