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.
except KeyError:
pass
else:
- for f in typing._cleanups:
- f()
+ typing._clear_caches()
import inspect
abs_classes = filter(inspect.isabstract, typing.__dict__.values())
"""
from abc import abstractmethod, ABCMeta
+import atexit
import collections
from collections import defaultdict
import collections.abc
_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.
--- /dev/null
+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.