Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GH-95899: fix asyncio.Runner to call set_event_loop once #95900

Merged
merged 2 commits into from
Aug 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions Lib/asyncio/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,6 @@ def run(self, coro, *, context=None):

self._interrupt_count = 0
try:
if self._set_event_loop:
events.set_event_loop(self._loop)
return self._loop.run_until_complete(task)
except exceptions.CancelledError:
if self._interrupt_count > 0:
Expand All @@ -136,7 +134,11 @@ def _lazy_init(self):
return
if self._loop_factory is None:
self._loop = events.new_event_loop()
self._set_event_loop = True
if not self._set_event_loop:
# Call set_event_loop only once to avoid calling
# attach_loop multiple times on child watchers
events.set_event_loop(self._loop)
self._set_event_loop = True
gvanrossum marked this conversation as resolved.
Show resolved Hide resolved
else:
self._loop = self._loop_factory()
if self._debug is not None:
Expand Down
14 changes: 14 additions & 0 deletions Lib/test/test_asyncio/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,20 @@ async def coro():
):
runner.run(coro())

def test_set_event_loop_called_once(self):
# See https://github.com/python/cpython/issues/95736
async def coro():
pass

policy = asyncio.get_event_loop_policy()
policy.set_event_loop = mock.Mock()
runner = asyncio.Runner()
runner.run(coro())
runner.run(coro())

self.assertEqual(1, policy.set_event_loop.call_count)
runner.close()


if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +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.