Skip to content

Commit

Permalink
Merge pull request #13 from Klavionik/support-async-callables
Browse files Browse the repository at this point in the history
Support async callable classes
  • Loading branch information
riga authored May 10, 2024
2 parents 68130d2 + 0ac934b commit 80d9faa
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion pymitter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ def _emit(self: EventEmitter, event: str, *args, **kwargs) -> list[Awaitable]:
self.off(listener.event, func=listener.func)

res = listener(*args, **kwargs)
if listener.is_coroutine:
if listener.is_coroutine or listener.is_async_callable:
awaitables.append(res)

return awaitables
Expand Down Expand Up @@ -410,6 +410,10 @@ def __init__(self: Listener, func: Callable, event: str, ttl: int) -> None:
def is_coroutine(self: Listener) -> bool:
return asyncio.iscoroutinefunction(self.func)

@property
def is_async_callable(self):
return hasattr(self.func, "__call__") and asyncio.iscoroutinefunction(self.func.__call__)

def __call__(self: Listener, *args, **kwargs) -> Any:
"""
Invokes the wrapped function when ttl is non-zero, decreases the ttl value when positive and
Expand Down
13 changes: 13 additions & 0 deletions tests/test_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,16 @@ async def test():
self.assertEqual(tuple(stack), ("emit_future_bar",))

await test()

def test_supports_async_callables(self):
ee = EventEmitter()
stack = []

class EventHandler:
async def __call__(self, arg):
stack.append(arg)

ee.on("event", EventHandler())

ee.emit("event", "arg")
self.assertEqual(stack, ["arg"])

0 comments on commit 80d9faa

Please sign in to comment.