Skip to content
This repository was archived by the owner on Jul 20, 2023. It is now read-only.

Commit b6af38b

Browse files
committed
feat(Dispatcher)!: add shortcut for adding callback to event
1 parent bf58b9e commit b6af38b

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

discatcore/impl/dispatcher.py

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,19 +50,19 @@ def new_event(self, name: str) -> Event:
5050
Returns:
5151
The new event created.
5252
"""
53-
if name in self.events:
54-
return self.events[name]
55-
5653
new_event = Event(name, self)
5754
self.events[name] = new_event
5855
return new_event
5956

60-
def add_event(self, event: Event) -> None:
57+
def add_event(self, event: Event, *, override: bool = True) -> None:
6158
"""Adds a new pre-existing event.
6259
6360
Args:
6461
event (Event): The event to add.
6562
"""
63+
if self.has_event(event.name) and not override:
64+
return
65+
6666
self.events[event.name] = event
6767

6868
def remove_event(self, name: str) -> None:
@@ -88,6 +88,32 @@ def has_event(self, name: str) -> bool:
8888
"""
8989
return name in self.events
9090

91+
def callback_for(
92+
self, event: str, *, one_shot: bool = False, parent: bool = False
93+
) -> Callable[[CoroFunc], Event]:
94+
"""A shortcut decorator to add a callback to an event.
95+
If the event does not exist already, then a new one will be created.
96+
97+
Args:
98+
event: The name of the event to get or create.
99+
one_shot: Whether or not the callback should be a one shot (which means the callback will be removed after running). Defaults to False.
100+
parent: Whether or not this callback contains a self parameter. Defaults to False.
101+
102+
Returns:
103+
A wrapper function that acts as the actual decorator.
104+
"""
105+
106+
def wrapper(coro: CoroFunc):
107+
if not self.has_event(event):
108+
event_cls = self.new_event(event)
109+
else:
110+
event_cls = self.events[event]
111+
112+
event_cls.add_callback(coro, one_shot=one_shot, parent=parent)
113+
return event_cls
114+
115+
return wrapper
116+
91117
# global error handler
92118

93119
async def error_handler(self, exception: Exception) -> None:

0 commit comments

Comments
 (0)