]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.14] gh-137384: fix crash when accessing warnings state late in runtime shutdown...
authorKumar Aditya <kumaraditya@python.org>
Fri, 22 Aug 2025 14:27:49 +0000 (19:57 +0530)
committerGitHub <noreply@github.com>
Fri, 22 Aug 2025 14:27:49 +0000 (17:27 +0300)
Lib/test/test_gc.py
Misc/NEWS.d/next/Core_and_Builtins/2025-08-22-11-39-40.gh-issue-137384.j4b_in.rst [new file with mode: 0644]
Python/pystate.c

index d9e9622992f5433c22ec95f9552a768044e0b0b6..969d290c259f734ef98a693cc3bf01406293cf8f 100644 (file)
@@ -1522,6 +1522,19 @@ class PythonFinalizationTests(unittest.TestCase):
         """)
         assert_python_ok("-c", code)
 
+    def test_warnings_fini(self):
+        # See https://github.com/python/cpython/issues/137384
+        code = textwrap.dedent('''
+            import asyncio
+            from contextvars import ContextVar
+
+            context_loop = ContextVar("context_loop", default=None)
+            loop = asyncio.new_event_loop()
+            context_loop.set(loop)
+        ''')
+
+        assert_python_ok("-c", code)
+
 
 def setUpModule():
     global enabled, debug
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-08-22-11-39-40.gh-issue-137384.j4b_in.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-08-22-11-39-40.gh-issue-137384.j4b_in.rst
new file mode 100644 (file)
index 0000000..583d751
--- /dev/null
@@ -0,0 +1 @@
+Fix a crash when using the :mod:`warnings` module in a finalizer at shutdown. Patch by Kumar Aditya.
index aa2c4bd51814c3b82e752079b1ed7bcac12fd45a..02621f36d91c8a46ed35eca4b0a050be155b93bf 100644 (file)
@@ -914,7 +914,6 @@ interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
     _Py_ClearExecutorDeletionList(interp);
 #endif
     _PyAST_Fini(interp);
-    _PyWarnings_Fini(interp);
     _PyAtExit_Fini(interp);
 
     // All Python types must be destroyed before the last GC collection. Python
@@ -925,6 +924,9 @@ interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
     _PyGC_CollectNoFail(tstate);
     _PyGC_Fini(interp);
 
+    // Finalize warnings after last gc so that any finalizers can
+    // access warnings state
+    _PyWarnings_Fini(interp);
     /* We don't clear sysdict and builtins until the end of this function.
        Because clearing other attributes can execute arbitrary Python code
        which requires sysdict and builtins. */