Skip to content

Commit b0f3b6d

Browse files
committed
Add Self to typing
1 parent 71a97c7 commit b0f3b6d

9 files changed

+66
-55
lines changed

pyee/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,6 @@
2727
2828
"""
2929

30-
from pyee.base import EventEmitter, PyeeError, PyeeException
30+
from pyee.base import EventEmitter, Handler, PyeeError, PyeeException
3131

32-
__all__ = ["EventEmitter", "PyeeError", "PyeeException"]
32+
__all__ = ["EventEmitter", "Handler", "PyeeError", "PyeeException"]

pyee/asyncio.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# -*- coding: utf-8 -*-
22

33
from asyncio import AbstractEventLoop, ensure_future, Future, iscoroutine, wait
4-
from typing import Any, Callable, cast, Dict, Optional, Set, Tuple
4+
from typing import Any, Callable, cast, Dict, Optional, Self, Set, Tuple
55

66
from pyee.base import EventEmitter
77

@@ -36,13 +36,13 @@ async def async_handler(*args, **kwargs):
3636
coroutine is scheduled in a fire-and-forget fashion.
3737
"""
3838

39-
def __init__(self, loop: Optional[AbstractEventLoop] = None):
39+
def __init__(self: Self, loop: Optional[AbstractEventLoop] = None) -> None:
4040
super(AsyncIOEventEmitter, self).__init__()
4141
self._loop: Optional[AbstractEventLoop] = loop
4242
self._waiting: Set[Future] = set()
4343

4444
def emit(
45-
self,
45+
self: Self,
4646
event: str,
4747
*args: Any,
4848
**kwargs: Any,
@@ -68,11 +68,11 @@ def emit(
6868
return super().emit(event, *args, **kwargs)
6969

7070
def _emit_run(
71-
self,
71+
self: Self,
7272
f: Callable,
7373
args: Tuple[Any, ...],
7474
kwargs: Dict[str, Any],
75-
):
75+
) -> None:
7676
try:
7777
coro: Any = f(*args, **kwargs)
7878
except Exception as exc:
@@ -105,7 +105,7 @@ def callback(f):
105105
fut.add_done_callback(callback)
106106
self._waiting.add(fut)
107107

108-
async def wait_for_complete(self):
108+
async def wait_for_complete(self: Self) -> None:
109109
"""Waits for all pending tasks to complete. For example:
110110
111111
```py
@@ -128,7 +128,7 @@ async def async_handler(*args, **kwargs):
128128
if self._waiting:
129129
await wait(self._waiting)
130130

131-
def cancel(self):
131+
def cancel(self: Self) -> None:
132132
"""Cancel all pending tasks. For example:
133133
134134
```py
@@ -153,7 +153,7 @@ async def async_handler(*args, **kwargs):
153153
self._waiting.clear()
154154

155155
@property
156-
def complete(self) -> bool:
156+
def complete(self: Self) -> bool:
157157
"""When true, there are no pending tasks, and execution is complete.
158158
For example:
159159

pyee/base.py

+18-17
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
List,
1010
Mapping,
1111
Optional,
12+
Self,
1213
Set,
1314
Tuple,
1415
TypeVar,
@@ -56,24 +57,24 @@ def on_error(message):
5657
your own exceptions, and treat them accordingly.
5758
"""
5859

59-
def __init__(self) -> None:
60+
def __init__(self: Self) -> None:
6061
self._events: Dict[
6162
str,
6263
"OrderedDict[Callable, Callable]",
6364
] = dict()
6465
self._lock: Lock = Lock()
6566

66-
def __getstate__(self) -> Mapping[str, Any]:
67+
def __getstate__(self: Self) -> Mapping[str, Any]:
6768
state = self.__dict__.copy()
6869
del state["_lock"]
6970
return state
7071

71-
def __setstate__(self, state: Mapping[str, Any]) -> None:
72+
def __setstate__(self: Self, state: Mapping[str, Any]) -> None:
7273
self.__dict__.update(state)
7374
self._lock = Lock()
7475

7576
def on(
76-
self, event: str, f: Optional[Handler] = None
77+
self: Self, event: str, f: Optional[Handler] = None
7778
) -> Union[Handler, Callable[[Handler], Handler]]:
7879
"""Registers the function `f` to the event name `event`, if provided.
7980
@@ -106,7 +107,7 @@ def data_handler(data):
106107
else:
107108
return self.add_listener(event, f)
108109

109-
def listens_to(self, event: str) -> Callable[[Handler], Handler]:
110+
def listens_to(self: Self, event: str) -> Callable[[Handler], Handler]:
110111
"""Returns a decorator which will register the decorated function to
111112
the event name `event`:
112113
@@ -126,7 +127,7 @@ def on(f: Handler) -> Handler:
126127

127128
return on
128129

129-
def add_listener(self, event: str, f: Handler) -> Handler:
130+
def add_listener(self: Self, event: str, f: Handler) -> Handler:
130131
"""Register the function `f` to the event name `event`:
131132
132133
```
@@ -142,7 +143,7 @@ def data_handler(data):
142143
self._add_event_handler(event, f, f)
143144
return f
144145

145-
def _add_event_handler(self, event: str, k: Callable, v: Callable):
146+
def _add_event_handler(self: Self, event: str, k: Callable, v: Callable):
146147
# Fire 'new_listener' *before* adding the new listener!
147148
self.emit("new_listener", event, k)
148149

@@ -156,26 +157,26 @@ def _add_event_handler(self, event: str, k: Callable, v: Callable):
156157
self._events[event][k] = v
157158

158159
def _emit_run(
159-
self,
160+
self: Self,
160161
f: Callable,
161162
args: Tuple[Any, ...],
162163
kwargs: Dict[str, Any],
163164
) -> None:
164165
f(*args, **kwargs)
165166

166-
def event_names(self) -> Set[str]:
167+
def event_names(self: Self) -> Set[str]:
167168
"""Get a set of events that this emitter is listening to."""
168169
return set(self._events.keys())
169170

170-
def _emit_handle_potential_error(self, event: str, error: Any) -> None:
171+
def _emit_handle_potential_error(self: Self, event: str, error: Any) -> None:
171172
if event == "error":
172173
if isinstance(error, Exception):
173174
raise error
174175
else:
175176
raise PyeeError(f"Uncaught, unspecified 'error' event: {error}")
176177

177178
def _call_handlers(
178-
self,
179+
self: Self,
179180
event: str,
180181
args: Tuple[Any, ...],
181182
kwargs: Dict[str, Any],
@@ -191,7 +192,7 @@ def _call_handlers(
191192
return handled
192193

193194
def emit(
194-
self,
195+
self: Self,
195196
event: str,
196197
*args: Any,
197198
**kwargs: Any,
@@ -217,7 +218,7 @@ def emit(
217218
return handled
218219

219220
def once(
220-
self,
221+
self: Self,
221222
event: str,
222223
f: Optional[Callable] = None,
223224
) -> Callable:
@@ -249,18 +250,18 @@ def g(
249250
else:
250251
return _wrapper(f)
251252

252-
def _remove_listener(self, event: str, f: Callable) -> None:
253+
def _remove_listener(self: Self, event: str, f: Callable) -> None:
253254
"""Naked unprotected removal."""
254255
self._events[event].pop(f)
255256
if not len(self._events[event]):
256257
del self._events[event]
257258

258-
def remove_listener(self, event: str, f: Callable) -> None:
259+
def remove_listener(self: Self, event: str, f: Callable) -> None:
259260
"""Removes the function `f` from `event`."""
260261
with self._lock:
261262
self._remove_listener(event, f)
262263

263-
def remove_all_listeners(self, event: Optional[str] = None) -> None:
264+
def remove_all_listeners(self: Self, event: Optional[str] = None) -> None:
264265
"""Remove all listeners attached to `event`.
265266
If `event` is `None`, remove all listeners on all events.
266267
"""
@@ -270,6 +271,6 @@ def remove_all_listeners(self, event: Optional[str] = None) -> None:
270271
else:
271272
self._events = dict()
272273

273-
def listeners(self, event: str) -> List[Callable]:
274+
def listeners(self: Self, event: str) -> List[Callable]:
274275
"""Returns a list of all listeners registered to the `event`."""
275276
return list(self._events.get(event, OrderedDict()).keys())

pyee/cls.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from dataclasses import dataclass
22
from functools import wraps
3-
from typing import Callable, List, Type, TypeVar
3+
from typing import Any, Callable, Iterator, List, Type, TypeVar
44

55
from pyee import EventEmitter
66

@@ -12,13 +12,13 @@ class Handler:
1212

1313

1414
class Handlers:
15-
def __init__(self):
15+
def __init__(self) -> None:
1616
self._handlers: List[Handler] = []
1717

18-
def append(self, handler):
18+
def append(self, handler) -> None:
1919
self._handlers.append(handler)
2020

21-
def __iter__(self):
21+
def __iter__(self) -> Iterator[Handler]:
2222
return iter(self._handlers)
2323

2424
def reset(self):
@@ -41,9 +41,9 @@ def decorator(method: Callable) -> Callable:
4141
return decorator
4242

4343

44-
def _bind(self, method):
44+
def _bind(self: Any, method: Any) -> Any:
4545
@wraps(method)
46-
def bound(*args, **kwargs):
46+
def bound(*args, **kwargs) -> Any:
4747
return method(self, *args, **kwargs)
4848

4949
return bound
@@ -103,7 +103,7 @@ async def event_handler(self, *args, **kwargs):
103103
og_init: Callable = cls.__init__
104104

105105
@wraps(cls.__init__)
106-
def init(self, *args, **kwargs):
106+
def init(self: Any, *args: Any, **kwargs: Any) -> None:
107107
og_init(self, *args, **kwargs)
108108
if not hasattr(self, "event_emitter"):
109109
self.event_emitter = EventEmitter()

pyee/executor.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from concurrent.futures import Executor, Future, ThreadPoolExecutor
44
from types import TracebackType
5-
from typing import Any, Callable, Dict, Optional, Tuple, Type
5+
from typing import Any, Callable, Dict, Optional, Self, Tuple, Type
66

77
from pyee.base import EventEmitter
88

@@ -44,19 +44,19 @@ def handler(data):
4444
No effort is made to ensure thread safety, beyond using an executor.
4545
"""
4646

47-
def __init__(self, executor: Optional[Executor] = None):
47+
def __init__(self: Self, executor: Optional[Executor] = None) -> None:
4848
super(ExecutorEventEmitter, self).__init__()
4949
if executor:
5050
self._executor: Executor = executor
5151
else:
5252
self._executor = ThreadPoolExecutor()
5353

5454
def _emit_run(
55-
self,
55+
self: Self,
5656
f: Callable,
5757
args: Tuple[Any, ...],
5858
kwargs: Dict[str, Any],
59-
):
59+
) -> None:
6060
future: Future = self._executor.submit(f, *args, **kwargs)
6161

6262
@future.add_done_callback
@@ -67,15 +67,15 @@ def _callback(f: Future) -> None:
6767
elif exc is not None:
6868
raise exc
6969

70-
def shutdown(self, wait: bool = True) -> None:
70+
def shutdown(self: Self, wait: bool = True) -> None:
7171
"""Call `shutdown` on the internal executor."""
7272

7373
self._executor.shutdown(wait=wait)
7474

75-
def __enter__(self) -> "ExecutorEventEmitter":
75+
def __enter__(self: Self) -> "ExecutorEventEmitter":
7676
return self
7777

7878
def __exit__(
79-
self, type: Type[Exception], value: Exception, traceback: TracebackType
79+
self: Self, type: Type[Exception], value: Exception, traceback: TracebackType
8080
) -> Optional[bool]:
8181
self.shutdown()

pyee/trio.py

+17-7
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,17 @@
22

33
from contextlib import AbstractAsyncContextManager, asynccontextmanager
44
from types import TracebackType
5-
from typing import Any, AsyncGenerator, Awaitable, Callable, Dict, Optional, Tuple, Type
5+
from typing import (
6+
Any,
7+
AsyncGenerator,
8+
Awaitable,
9+
Callable,
10+
Dict,
11+
Optional,
12+
Self,
13+
Tuple,
14+
Type,
15+
)
616

717
import trio
818

@@ -50,7 +60,7 @@ async def handler(data):
5060
"""
5161

5262
def __init__(
53-
self,
63+
self: Self,
5464
nursery: Optional[Nursery] = None,
5565
manager: Optional["AbstractAsyncContextManager[trio.Nursery]"] = None,
5666
):
@@ -69,7 +79,7 @@ def __init__(
6979
self._manager = trio.open_nursery()
7080

7181
def _async_runner(
72-
self,
82+
self: Self,
7383
f: Callable,
7484
args: Tuple[Any, ...],
7585
kwargs: Dict[str, Any],
@@ -83,7 +93,7 @@ async def runner() -> None:
8393
return runner
8494

8595
def _emit_run(
86-
self,
96+
self: Self,
8797
f: Callable,
8898
args: Tuple[Any, ...],
8999
kwargs: Dict[str, Any],
@@ -94,7 +104,7 @@ def _emit_run(
94104

95105
@asynccontextmanager
96106
async def context(
97-
self,
107+
self: Self,
98108
) -> AsyncGenerator["TrioEventEmitter", None]:
99109
"""Returns an async contextmanager which manages the underlying
100110
nursery to the EventEmitter. The `TrioEventEmitter`'s
@@ -110,14 +120,14 @@ async def context(
110120
else:
111121
raise PyeeError("Uninitialized nursery or nursery manager")
112122

113-
async def __aenter__(self) -> "TrioEventEmitter":
123+
async def __aenter__(self: Self) -> "TrioEventEmitter":
114124
self._context: Optional[AbstractAsyncContextManager["TrioEventEmitter"]] = (
115125
self.context()
116126
)
117127
return await self._context.__aenter__()
118128

119129
async def __aexit__(
120-
self,
130+
self: Self,
121131
type: Optional[Type[BaseException]],
122132
value: Optional[BaseException],
123133
traceback: Optional[TracebackType],

0 commit comments

Comments
 (0)