Skip to content

Commit 78caa71

Browse files
authored
Merge pull request #127 from Vizonex/unify-uvloop
sync up with uvloop fork that I have to allow people to start testing it.
2 parents fc40ffc + 8cb2a3f commit 78caa71

29 files changed

+799
-1065
lines changed

winloop/__init__.py

Lines changed: 48 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import asyncio as __asyncio
2-
import collections.abc as _collections_abc
32
import typing as _typing
43
import sys as _sys
54
import warnings as _warnings
@@ -9,7 +8,7 @@
98
from ._version import __version__ # NOQA
109

1110

12-
__all__: tuple[str, ...] = ("new_event_loop", "run")
11+
__all__: _typing.Tuple[str, ...] = ('new_event_loop', 'run')
1312
_AbstractEventLoop = __asyncio.AbstractEventLoop
1413

1514

@@ -26,16 +25,16 @@ def new_event_loop() -> Loop:
2625

2726

2827
if _typing.TYPE_CHECKING:
29-
3028
def run(
31-
main: _collections_abc.Coroutine[_typing.Any, _typing.Any, _T],
29+
main: _typing.Coroutine[_typing.Any, _typing.Any, _T],
3230
*,
33-
loop_factory: _collections_abc.Callable[[], Loop] | None = new_event_loop,
34-
debug: bool | None = None,
31+
loop_factory: _typing.Optional[
32+
_typing.Callable[[], Loop]
33+
] = new_event_loop,
34+
debug: _typing.Optional[bool]=None,
3535
) -> _T:
3636
"""The preferred way of running a coroutine with winloop."""
3737
else:
38-
3938
def run(main, *, loop_factory=new_event_loop, debug=None, **run_kwargs):
4039
"""The preferred way of running a coroutine with winloop."""
4140

@@ -45,7 +44,7 @@ async def wrapper():
4544
# is using `winloop.run()` intentionally.
4645
loop = __asyncio._get_running_loop()
4746
if not isinstance(loop, Loop):
48-
raise TypeError("winloop.run() uses a non-winloop event loop")
47+
raise TypeError('winloop.run() uses a non-winloop event loop')
4948
return await main
5049

5150
vi = _sys.version_info[:2]
@@ -55,11 +54,12 @@ async def wrapper():
5554

5655
if __asyncio._get_running_loop() is not None:
5756
raise RuntimeError(
58-
"asyncio.run() cannot be called from a running event loop"
59-
)
57+
"asyncio.run() cannot be called from a running event loop")
6058

6159
if not __asyncio.iscoroutine(main):
62-
raise ValueError("a coroutine was expected, got {!r}".format(main))
60+
raise ValueError(
61+
"a coroutine was expected, got {!r}".format(main)
62+
)
6363

6464
loop = loop_factory()
6565
try:
@@ -71,27 +71,33 @@ async def wrapper():
7171
try:
7272
_cancel_all_tasks(loop)
7373
loop.run_until_complete(loop.shutdown_asyncgens())
74-
if hasattr(loop, "shutdown_default_executor"):
75-
loop.run_until_complete(loop.shutdown_default_executor())
74+
if hasattr(loop, 'shutdown_default_executor'):
75+
loop.run_until_complete(
76+
loop.shutdown_default_executor()
77+
)
7678
finally:
7779
__asyncio.set_event_loop(None)
7880
loop.close()
7981

8082
elif vi == (3, 11):
8183
if __asyncio._get_running_loop() is not None:
8284
raise RuntimeError(
83-
"asyncio.run() cannot be called from a running event loop"
84-
)
85+
"asyncio.run() cannot be called from a running event loop")
8586

8687
with __asyncio.Runner(
87-
loop_factory=loop_factory, debug=debug, **run_kwargs
88+
loop_factory=loop_factory,
89+
debug=debug,
90+
**run_kwargs
8891
) as runner:
8992
return runner.run(wrapper())
9093

9194
else:
9295
assert vi >= (3, 12)
9396
return __asyncio.run(
94-
wrapper(), loop_factory=loop_factory, debug=debug, **run_kwargs
97+
wrapper(),
98+
loop_factory=loop_factory,
99+
debug=debug,
100+
**run_kwargs
95101
)
96102

97103

@@ -105,22 +111,22 @@ def _cancel_all_tasks(loop: _AbstractEventLoop) -> None:
105111
for task in to_cancel:
106112
task.cancel()
107113

108-
loop.run_until_complete(__asyncio.gather(*to_cancel, return_exceptions=True))
114+
loop.run_until_complete(
115+
__asyncio.gather(*to_cancel, return_exceptions=True)
116+
)
109117

110118
for task in to_cancel:
111119
if task.cancelled():
112120
continue
113121
if task.exception() is not None:
114-
loop.call_exception_handler(
115-
{
116-
"message": "unhandled exception during asyncio.run() shutdown",
117-
"exception": task.exception(),
118-
"task": task,
119-
}
120-
)
122+
loop.call_exception_handler({
123+
'message': 'unhandled exception during asyncio.run() shutdown',
124+
'exception': task.exception(),
125+
'task': task,
126+
})
121127

122128

123-
_deprecated_names = ("install", "EventLoopPolicy")
129+
_deprecated_names = ('install', 'EventLoopPolicy')
124130

125131

126132
if _sys.version_info[:2] < (3, 16):
@@ -146,16 +152,16 @@ def install() -> None:
146152
"""
147153
if _sys.version_info[:2] >= (3, 12):
148154
_warnings.warn(
149-
"winloop.install() is deprecated in favor of winloop.run() "
150-
"starting with Python 3.12.",
155+
'winloop.install() is deprecated in favor of winloop.run() '
156+
'starting with Python 3.12.',
151157
DeprecationWarning,
152158
stacklevel=1,
153159
)
154160
__asyncio.set_event_loop_policy(EventLoopPolicy())
155161

156162
class EventLoopPolicy(
157163
# This is to avoid a mypy error about AbstractEventLoopPolicy
158-
getattr(__asyncio, "AbstractEventLoopPolicy") # type: ignore[misc]
164+
getattr(__asyncio, 'AbstractEventLoopPolicy') # type: ignore[misc]
159165
):
160166
"""Event loop policy for winloop.
161167
@@ -177,12 +183,16 @@ def _loop_factory(self) -> Loop:
177183
# marked as abstract in typeshed, we have to put them in so mypy
178184
# thinks the base methods are overridden. This is the same approach
179185
# taken for the Windows event loop policy classes in typeshed.
180-
def get_child_watcher(self) -> _typing.NoReturn: ...
186+
def get_child_watcher(self) -> _typing.NoReturn:
187+
...
181188

182-
def set_child_watcher(self, watcher: _typing.Any) -> _typing.NoReturn: ...
189+
def set_child_watcher(
190+
self, watcher: _typing.Any
191+
) -> _typing.NoReturn:
192+
...
183193

184194
class _Local(threading.local):
185-
_loop: _AbstractEventLoop | None = None
195+
_loop: _typing.Optional[_AbstractEventLoop] = None
186196

187197
def __init__(self) -> None:
188198
self._local = self._Local()
@@ -194,13 +204,15 @@ def get_event_loop(self) -> _AbstractEventLoop:
194204
"""
195205
if self._local._loop is None:
196206
raise RuntimeError(
197-
"There is no current event loop in thread %r."
207+
'There is no current event loop in thread %r.'
198208
% threading.current_thread().name
199209
)
200210

201211
return self._local._loop
202212

203-
def set_event_loop(self, loop: _AbstractEventLoop | None) -> None:
213+
def set_event_loop(
214+
self, loop: _typing.Optional[_AbstractEventLoop]
215+
) -> None:
204216
"""Set the event loop."""
205217
if loop is not None and not isinstance(loop, _AbstractEventLoop):
206218
raise TypeError(
@@ -216,6 +228,6 @@ def new_event_loop(self) -> Loop:
216228
"""
217229
return self._loop_factory()
218230

219-
globals()["install"] = install
220-
globals()["EventLoopPolicy"] = EventLoopPolicy
231+
globals()['install'] = install
232+
globals()['EventLoopPolicy'] = EventLoopPolicy
221233
return globals()[name]

0 commit comments

Comments
 (0)