Skip to content

Commit d619015

Browse files
[3.14] gh-137384: fix crash when accessing warnings state late in runtime shutdown (GH-138027) (#138065)
1 parent c213eb9 commit d619015

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

Lib/test/test_gc.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1522,6 +1522,19 @@ def test_ast_fini(self):
15221522
""")
15231523
assert_python_ok("-c", code)
15241524

1525+
def test_warnings_fini(self):
1526+
# See https://github.com/python/cpython/issues/137384
1527+
code = textwrap.dedent('''
1528+
import asyncio
1529+
from contextvars import ContextVar
1530+
1531+
context_loop = ContextVar("context_loop", default=None)
1532+
loop = asyncio.new_event_loop()
1533+
context_loop.set(loop)
1534+
''')
1535+
1536+
assert_python_ok("-c", code)
1537+
15251538

15261539
def setUpModule():
15271540
global enabled, debug
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a crash when using the :mod:`warnings` module in a finalizer at shutdown. Patch by Kumar Aditya.

Python/pystate.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -914,7 +914,6 @@ interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
914914
_Py_ClearExecutorDeletionList(interp);
915915
#endif
916916
_PyAST_Fini(interp);
917-
_PyWarnings_Fini(interp);
918917
_PyAtExit_Fini(interp);
919918

920919
// All Python types must be destroyed before the last GC collection. Python
@@ -925,6 +924,9 @@ interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
925924
_PyGC_CollectNoFail(tstate);
926925
_PyGC_Fini(interp);
927926

927+
// Finalize warnings after last gc so that any finalizers can
928+
// access warnings state
929+
_PyWarnings_Fini(interp);
928930
/* We don't clear sysdict and builtins until the end of this function.
929931
Because clearing other attributes can execute arbitrary Python code
930932
which requires sysdict and builtins. */

0 commit comments

Comments
 (0)