Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a type parameter for Handler in on/add_listener/listens_to #107

Merged
merged 1 commit into from Jan 18, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 10 additions & 5 deletions pyee/base.py
Expand Up @@ -2,13 +2,16 @@

from collections import OrderedDict
from threading import Lock
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, TypeVar, Union


class PyeeException(Exception):
"""An exception internal to pyee."""


Handler = TypeVar(name="Handler", bound=Callable)


class EventEmitter:
"""The base event emitter class. All other event emitters inherit from
this class.
Expand Down Expand Up @@ -43,7 +46,9 @@ def __init__(self) -> None:
] = dict()
self._lock: Lock = Lock()

def on(self, event: str, f: Optional[Callable] = None) -> Callable:
def on(
self, event: str, f: Optional[Handler] = None
) -> Union[Handler, Callable[[Handler], Handler]]:
"""Registers the function ``f`` to the event name ``event``, if provided.

If ``f`` isn't provided, this method calls ``EventEmitter#listens_to`, and
Expand Down Expand Up @@ -71,7 +76,7 @@ def data_handler(data):
else:
return self.add_listener(event, f)

def listens_to(self, event: str) -> Callable[[Callable], Callable]:
def listens_to(self, event: str) -> Callable[[Handler], Handler]:
"""Returns a decorator which will register the decorated function to
the event name ``event``. Usage::

Expand All @@ -83,13 +88,13 @@ def data_handler(data):
type safety over ``EventEmitter#on``.
"""

def on(f: Callable) -> Callable:
def on(f: Handler) -> Handler:
self._add_event_handler(event, f, f)
return f

return on

def add_listener(self, event: str, f: Callable) -> Callable:
def add_listener(self, event: str, f: Handler) -> Handler:
"""Register the function ``f`` to the event name ``event``. This method
doesn't afford a narrower return type than ``EventEmitter#on`` but is a
natural pair to ``EventEmitter#listens_to`` and if nothing else has
Expand Down