From b6beea48c98ae65b4cb52d02539b6725e109fd37 Mon Sep 17 00:00:00 2001 From: Kumar Aditya <59607654+kumaraditya303@users.noreply.github.com> Date: Thu, 11 Aug 2022 18:47:17 +0000 Subject: [PATCH 1/2] fix asyncio.Runner call set_event_loop once --- Lib/asyncio/runners.py | 8 +++++--- Lib/test/test_asyncio/test_runners.py | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Lib/asyncio/runners.py b/Lib/asyncio/runners.py index a8b74d532fcd3e..840b133df83ee6 100644 --- a/Lib/asyncio/runners.py +++ b/Lib/asyncio/runners.py @@ -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: @@ -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 else: self._loop = self._loop_factory() if self._debug is not None: diff --git a/Lib/test/test_asyncio/test_runners.py b/Lib/test/test_asyncio/test_runners.py index d61d073a367492..1308b7e2ba4f82 100644 --- a/Lib/test/test_asyncio/test_runners.py +++ b/Lib/test/test_asyncio/test_runners.py @@ -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() From 843b612ce36214025ad8bbb26eaa7119750d194f Mon Sep 17 00:00:00 2001 From: "blurb-it[bot]" <43283697+blurb-it[bot]@users.noreply.github.com> Date: Thu, 11 Aug 2022 18:52:18 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=93=9C=F0=9F=A4=96=20Added=20by=20blu?= =?UTF-8?q?rb=5Fit.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../next/Library/2022-08-11-18-52-17.gh-issue-95899._Bi4uG.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2022-08-11-18-52-17.gh-issue-95899._Bi4uG.rst diff --git a/Misc/NEWS.d/next/Library/2022-08-11-18-52-17.gh-issue-95899._Bi4uG.rst b/Misc/NEWS.d/next/Library/2022-08-11-18-52-17.gh-issue-95899._Bi4uG.rst new file mode 100644 index 00000000000000..d2386cf3ae2296 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2022-08-11-18-52-17.gh-issue-95899._Bi4uG.rst @@ -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.