Skip to content

Commit 14fea6b

Browse files
GH-93896: AAlways set event loop in asyncio.run and IsolatedAsyncioTestCase (#94593)
1 parent e925241 commit 14fea6b

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

Lib/asyncio/runners.py

+6
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ def __init__(self, *, debug=None, loop_factory=None):
5252
self._loop = None
5353
self._context = None
5454
self._interrupt_count = 0
55+
self._set_event_loop = False
5556

5657
def __enter__(self):
5758
self._lazy_init()
@@ -70,6 +71,8 @@ def close(self):
7071
loop.run_until_complete(loop.shutdown_asyncgens())
7172
loop.run_until_complete(loop.shutdown_default_executor())
7273
finally:
74+
if self._set_event_loop:
75+
events.set_event_loop(None)
7376
loop.close()
7477
self._loop = None
7578
self._state = _State.CLOSED
@@ -111,6 +114,8 @@ def run(self, coro, *, context=None):
111114

112115
self._interrupt_count = 0
113116
try:
117+
if self._set_event_loop:
118+
events.set_event_loop(self._loop)
114119
return self._loop.run_until_complete(task)
115120
except exceptions.CancelledError:
116121
if self._interrupt_count > 0 and task.uncancel() == 0:
@@ -130,6 +135,7 @@ def _lazy_init(self):
130135
return
131136
if self._loop_factory is None:
132137
self._loop = events.new_event_loop()
138+
self._set_event_loop = True
133139
else:
134140
self._loop = self._loop_factory()
135141
if self._debug is not None:

Lib/test/test_asyncio/test_runners.py

+12
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,18 @@ async def main():
198198
self.assertIsNone(spinner.ag_frame)
199199
self.assertFalse(spinner.ag_running)
200200

201+
def test_asyncio_run_set_event_loop(self):
202+
#See https://github.com/python/cpython/issues/93896
203+
204+
async def main():
205+
await asyncio.sleep(0)
206+
return 42
207+
208+
policy = asyncio.get_event_loop_policy()
209+
policy.set_event_loop = mock.Mock()
210+
asyncio.run(main())
211+
self.assertTrue(policy.set_event_loop.called)
212+
201213

202214
class RunnerTests(BaseTest):
203215

Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :func:`asyncio.run` and :class:`unittest.IsolatedAsyncioTestCase` to always the set event loop as it was done in Python 3.10 and earlier. Patch by Kumar Aditya.

0 commit comments

Comments
 (0)