-
Notifications
You must be signed in to change notification settings - Fork 187
/
events.py
37 lines (27 loc) · 1 KB
/
events.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from __future__ import annotations
from collections.abc import Callable
class Event:
def __init__(self) -> None:
"""Initialize the object."""
self._handlers = []
def __iadd__(self, handler: Callable):
"""Add item."""
self.add_handler(handler)
return self
def __isub__(self, handler: Callable):
"""Subtract item."""
self._handlers.remove(handler)
return self
def add_handler(self, handler: Callable) -> None:
"""Adds a handler that will be executed when this event is fired.
Args:
handler: a function which matches the signature fired by this event
"""
self._handlers.append(handler)
def clear_handlers(self) -> None:
"""Clear all handlers."""
self._handlers.clear()
def fire(self, *args, **kwargs) -> None:
"""Fires an event, calling all handlers with the passed arguments."""
for eventhandler in self._handlers:
eventhandler(*args, **kwargs)