]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-151728: Clear the typing caches at interpreter shutdown (GH-154858)
authorWenzel Jakob <wenzel.jakob@epfl.ch>
Thu, 30 Jul 2026 12:00:08 +0000 (14:00 +0200)
committerGitHub <noreply@github.com>
Thu, 30 Jul 2026 12:00:08 +0000 (14:00 +0200)
The typing module caches every subscripted type. When an extension module
leaks a reference to typing, these caches also keep types owned by other
(correct) extension modules alive past interpreter shutdown, where nothing
can free them anymore. The cache_clear callables are already collected in
typing._cleanups, so registering them with atexit is enough to avoid this.

Lib/test/libregrtest/utils.py
Lib/typing.py
Misc/NEWS.d/next/Library/2026-07-29-11-05-00.gh-issue-151728.Kq3vTn.rst [new file with mode: 0644]

index 32f02429ff3307644d73ef945c99dd50e1bdda0b..892d204700179f65b6779cf6a7a5e2087d62d6a0 100644 (file)
@@ -272,8 +272,7 @@ def clear_caches():
     except KeyError:
         pass
     else:
-        for f in typing._cleanups:
-            f()
+        typing._clear_caches()
 
         import inspect
         abs_classes = filter(inspect.isabstract, typing.__dict__.values())
index 054420865d7fb50ce15286cef23471c0b1c636f0..809c0ff88607a59067cd0061222063eb072bbad0 100644 (file)
@@ -19,6 +19,7 @@ that may be changed without notice. Use at your own risk!
 """
 
 from abc import abstractmethod, ABCMeta
+import atexit
 import collections
 from collections import defaultdict
 import collections.abc
@@ -392,6 +393,16 @@ _cleanups = []
 _caches = {}
 
 
+def _clear_caches():
+    for cleanup in _cleanups:
+        cleanup()
+
+
+# Release the LRU caches at shutdown, they otherwise redistribute reference
+# leaks of one extension to types of unrelated ones. See GH-151728.
+atexit.register(_clear_caches)
+
+
 def _tp_cache(func=None, /, *, typed=False):
     """Internal wrapper caching __getitem__ of generic types.
 
diff --git a/Misc/NEWS.d/next/Library/2026-07-29-11-05-00.gh-issue-151728.Kq3vTn.rst b/Misc/NEWS.d/next/Library/2026-07-29-11-05-00.gh-issue-151728.Kq3vTn.rst
new file mode 100644 (file)
index 0000000..39c63a1
--- /dev/null
@@ -0,0 +1,4 @@
+Clear the internal :mod:`typing` caches from an exit handler. Previously, an
+extension module that leaked a reference to :mod:`typing` would also keep every
+subscripted type alive past interpreter shutdown, including types owned by
+unrelated extension modules.