Skip to content

Commit 18053dd

Browse files
committed
Create missing loop in get_event_loop in main thread
This fixes issue #702.
1 parent 5910a18 commit 18053dd

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

uvloop/__init__.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio as __asyncio
2+
from types import FrameType
23
import typing as _typing
34
import sys as _sys
45
import warnings as _warnings
@@ -202,6 +203,33 @@ def get_event_loop(self) -> _AbstractEventLoop:
202203
203204
Returns an instance of EventLoop or raises an exception.
204205
"""
206+
if (
207+
self._local._loop is None
208+
and threading.current_thread() is threading.main_thread()
209+
):
210+
# Replicate the behavior of asyncio.get_event_loop() as closely
211+
# as possible, including the warning and stack level.
212+
stacklevel = 2
213+
try:
214+
f: _typing.Optional[FrameType] = _sys._getframe(1)
215+
except AttributeError:
216+
pass
217+
else:
218+
# Move up the call stack so that the warning is attached
219+
# to the line outside uvloop itself.
220+
while f is not None:
221+
module = f.f_globals['__name__']
222+
if not (module == 'uvloop' or module.startswith('uvloop.')):
223+
break
224+
f = f.f_back
225+
stacklevel += 1
226+
_warnings.warn(
227+
'There is no current event loop',
228+
DeprecationWarning,
229+
stacklevel=stacklevel
230+
)
231+
self._local._loop = self._loop_factory()
232+
205233
if self._local._loop is None:
206234
raise RuntimeError(
207235
'There is no current event loop in thread %r.'

0 commit comments

Comments
 (0)