internal: add a trigger_async method for events

This commit is contained in:
mathieui 2022-02-06 18:54:50 +01:00
parent d35c0564b3
commit 22093250ef

View file

@ -8,10 +8,14 @@ Defines the EventHandler class.
The list of available events is here:
http://poezio.eu/doc/en/plugins.html#_poezio_events
"""
import logging
from collections import OrderedDict
from inspect import iscoroutinefunction
from typing import Callable, Dict, List
log = logging.getLogger(__name__)
class EventHandler:
"""
@ -75,6 +79,20 @@ class EventHandler:
return True
async def trigger_async(self, name: str, *args, **kwargs):
"""
Call all the callbacks associated to the given event name.
"""
callbacks = self.events.get(name, None)
if callbacks is None:
return
for priority in callbacks.values():
for callback in priority:
if iscoroutinefunction(callback):
await callback(*args, **kwargs)
else:
callback(*args, **kwargs)
def trigger(self, name: str, *args, **kwargs):
"""
Call all the callbacks associated to the given event name.
@ -84,7 +102,11 @@ class EventHandler:
return
for priority in callbacks.values():
for callback in priority:
callback(*args, **kwargs)
if not iscoroutinefunction(callback):
callback(*args, **kwargs)
else:
log.error(f'async event handler {callback} '
'called in sync trigger!')
def del_event_handler(self, name: str, callback: Callable):
"""