Skip to content

Commit b9bcd02

Browse files
gh-137384: fix crash when accessing warnings state late in runtime shutdown (#138027)
1 parent 5b0f00e commit b9bcd02

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

Lib/test/test_gc.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1580,6 +1580,19 @@ def test_ast_fini(self):
15801580
""")
15811581
assert_python_ok("-c", code)
15821582

1583+
def test_warnings_fini(self):
1584+
# See https://github.com/python/cpython/issues/137384
1585+
code = textwrap.dedent('''
1586+
import asyncio
1587+
from contextvars import ContextVar
1588+
1589+
context_loop = ContextVar("context_loop", default=None)
1590+
loop = asyncio.new_event_loop()
1591+
context_loop.set(loop)
1592+
''')
1593+
1594+
assert_python_ok("-c", code)
1595+
15831596

15841597
def setUpModule():
15851598
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: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -805,7 +805,6 @@ interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
805805
_Py_ClearExecutorDeletionList(interp);
806806
#endif
807807
_PyAST_Fini(interp);
808-
_PyWarnings_Fini(interp);
809808
_PyAtExit_Fini(interp);
810809

811810
// All Python types must be destroyed before the last GC collection. Python
@@ -815,6 +814,10 @@ interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
815814
/* Last garbage collection on this interpreter */
816815
_PyGC_CollectNoFail(tstate);
817816
_PyGC_Fini(interp);
817+
818+
// Finalize warnings after last gc so that any finalizers can
819+
// access warnings state
820+
_PyWarnings_Fini(interp);
818821
struct _PyExecutorObject *cold = interp->cold_executor;
819822
if (cold != NULL) {
820823
interp->cold_executor = NULL;

0 commit comments

Comments
 (0)