Skip to content

[3.14] gh-137384: fix crash when accessing warnings state late in runtime shutdown (GH-138027) #138065

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Lib/test/test_gc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1522,6 +1522,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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix a crash when using the :mod:`warnings` module in a finalizer at shutdown. Patch by Kumar Aditya.
4 changes: 3 additions & 1 deletion Python/pystate.c
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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. */
Expand Down
Loading