From 22093250ef543dfd68fc31500b39834ab5143704 Mon Sep 17 00:00:00 2001 From: mathieui Date: Sun, 6 Feb 2022 18:54:50 +0100 Subject: internal: add a trigger_async method for events --- poezio/events.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/poezio/events.py b/poezio/events.py index 63782836..a846d38d 100644 --- a/poezio/events.py +++ b/poezio/events.py @@ -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): """ -- cgit v1.2.3