]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-130145: fix `loop.run_forever` when loop is already running (#130146)
authorKumar Aditya <kumaraditya@python.org>
Sat, 15 Feb 2025 09:31:53 +0000 (15:01 +0530)
committerGitHub <noreply@github.com>
Sat, 15 Feb 2025 09:31:53 +0000 (15:01 +0530)
Lib/asyncio/base_events.py
Lib/test/test_asyncio/test_events.py
Misc/NEWS.d/next/Library/2025-02-15-07-50-37.gh-issue-130145.I0CkV0.rst [new file with mode: 0644]

index ed852421e4421216df98d331263a1f6f4bd9a21f..546361f80b1f4766a12802ceec62696586641ed2 100644 (file)
@@ -671,8 +671,8 @@ class BaseEventLoop(events.AbstractEventLoop):
 
     def run_forever(self):
         """Run until stop() is called."""
+        self._run_forever_setup()
         try:
-            self._run_forever_setup()
             while True:
                 self._run_once()
                 if self._stopping:
index 3838993fa8c6a9cb27cb290848cd452ad6ec45ad..35069608d8163a5dd4d89477bf9e5b516fee9316 100644 (file)
@@ -3004,6 +3004,22 @@ class GetEventLoopTestsMixin:
                 self.loop.run_until_complete(main()),
                 'hello')
 
+    def test_get_running_loop_already_running(self):
+        async def main():
+            running_loop = asyncio.get_running_loop()
+            loop = asyncio.new_event_loop()
+            try:
+                loop.run_forever()
+            except RuntimeError:
+                pass
+            else:
+                self.fail("RuntimeError not raised")
+
+            self.assertIs(asyncio.get_running_loop(), running_loop)
+
+        self.loop.run_until_complete(main())
+
+
     def test_get_event_loop_returns_running_loop(self):
         class TestError(Exception):
             pass
diff --git a/Misc/NEWS.d/next/Library/2025-02-15-07-50-37.gh-issue-130145.I0CkV0.rst b/Misc/NEWS.d/next/Library/2025-02-15-07-50-37.gh-issue-130145.I0CkV0.rst
new file mode 100644 (file)
index 0000000..9c8c469
--- /dev/null
@@ -0,0 +1 @@
+Fix :meth:`!asyncio.AbstractEventloop.run_forever` when another loop is already running.