Skip to content

Commit 8bd7a0b

Browse files
GH-95899: fix asyncio.Runner to call set_event_loop only once (GH-95900) (#96003)
(cherry picked from commit 914f636) Co-authored-by: Kumar Aditya <[email protected]>
1 parent 3fa97b8 commit 8bd7a0b

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

Lib/asyncio/runners.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -115,8 +115,6 @@ def run(self, coro, *, context=None):
115115

116116
self._interrupt_count = 0
117117
try:
118-
if self._set_event_loop:
119-
events.set_event_loop(self._loop)
120118
return self._loop.run_until_complete(task)
121119
except exceptions.CancelledError:
122120
if self._interrupt_count > 0:
@@ -137,7 +135,11 @@ def _lazy_init(self):
137135
return
138136
if self._loop_factory is None:
139137
self._loop = events.new_event_loop()
140-
self._set_event_loop = True
138+
if not self._set_event_loop:
139+
# Call set_event_loop only once to avoid calling
140+
# attach_loop multiple times on child watchers
141+
events.set_event_loop(self._loop)
142+
self._set_event_loop = True
141143
else:
142144
self._loop = self._loop_factory()
143145
if self._debug is not None:

Lib/test/test_asyncio/test_runners.py

+14
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,20 @@ async def coro():
456456
):
457457
runner.run(coro())
458458

459+
def test_set_event_loop_called_once(self):
460+
# See https://github.com/python/cpython/issues/95736
461+
async def coro():
462+
pass
463+
464+
policy = asyncio.get_event_loop_policy()
465+
policy.set_event_loop = mock.Mock()
466+
runner = asyncio.Runner()
467+
runner.run(coro())
468+
runner.run(coro())
469+
470+
self.assertEqual(1, policy.set_event_loop.call_count)
471+
runner.close()
472+
459473

460474
if __name__ == '__main__':
461475
unittest.main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :class:`asyncio.Runner` to call :func:`asyncio.set_event_loop` only once to avoid calling :meth:`~asyncio.AbstractChildWatcher.attach_loop` multiple times on child watchers. Patch by Kumar Aditya.

0 commit comments

Comments
 (0)