]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-95899: fix asyncio.Runner to call set_event_loop only once (#95900)
authorKumar Aditya <59607654+kumaraditya303@users.noreply.github.com>
Mon, 15 Aug 2022 17:02:47 +0000 (22:32 +0530)
committerGitHub <noreply@github.com>
Mon, 15 Aug 2022 17:02:47 +0000 (10:02 -0700)
Lib/asyncio/runners.py
Lib/test/test_asyncio/test_runners.py
Misc/NEWS.d/next/Library/2022-08-11-18-52-17.gh-issue-95899._Bi4uG.rst [new file with mode: 0644]

index a8b74d532fcd3e292a3fb14ff86f4905ea17aeff..840b133df83ee6c72cb68faefb0cbf5793196fd5 100644 (file)
@@ -114,8 +114,6 @@ class Runner:
 
         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 @@ class Runner:
             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:
index d61d073a3674922b5a75a10914fd303d97ed473f..1308b7e2ba4f82836998abeb72a2593d52dcb4ac 100644 (file)
@@ -455,6 +455,20 @@ class RunnerTests(BaseTest):
             ):
                 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()
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 (file)
index 0000000..d2386cf
--- /dev/null
@@ -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.