https://github.com/python/cpython/commit/b9bcd02e9fe976e0a6a8e8a0b336d598b1d73b13
commit: b9bcd02e9fe976e0a6a8e8a0b336d598b1d73b13
branch: main
author: Kumar Aditya <[email protected]>
committer: kumaraditya303 <[email protected]>
date: 2025-08-22T19:10:43+05:30
summary:

gh-137384: fix crash when accessing warnings state late in runtime shutdown 
(#138027)

files:
A 
Misc/NEWS.d/next/Core_and_Builtins/2025-08-22-11-39-40.gh-issue-137384.j4b_in.rst
M Lib/test/test_gc.py
M Python/pystate.c

diff --git a/Lib/test/test_gc.py b/Lib/test/test_gc.py
index 7c9adf3049a131..4328909053465e 100644
--- a/Lib/test/test_gc.py
+++ b/Lib/test/test_gc.py
@@ -1580,6 +1580,19 @@ def test_ast_fini(self):
         """)
         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
index 00000000000000..583d751a460eb6
--- /dev/null
+++ 
b/Misc/NEWS.d/next/Core_and_Builtins/2025-08-22-11-39-40.gh-issue-137384.j4b_in.rst
@@ -0,0 +1 @@
+Fix a crash when using the :mod:`warnings` module in a finalizer at shutdown. 
Patch by Kumar Aditya.
diff --git a/Python/pystate.c b/Python/pystate.c
index 9091057f6f62cf..2465d8667472dc 100644
--- a/Python/pystate.c
+++ b/Python/pystate.c
@@ -805,7 +805,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
@@ -815,6 +814,10 @@ interpreter_clear(PyInterpreterState *interp, 
PyThreadState *tstate)
     /* Last garbage collection on this interpreter */
     _PyGC_CollectNoFail(tstate);
     _PyGC_Fini(interp);
+
+    // Finalize warnings after last gc so that any finalizers can
+    // access warnings state
+    _PyWarnings_Fini(interp);
     struct _PyExecutorObject *cold = interp->cold_executor;
     if (cold != NULL) {
         interp->cold_executor = NULL;

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to