Skip to content

Commit a191941

Browse files
committed
gh-151728: Clear the typing caches at interpreter shutdown
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.
1 parent 4b82c87 commit a191941

2 files changed

Lines changed: 15 additions & 0 deletions

File tree

Lib/typing.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
"""
2020

2121
from abc import abstractmethod, ABCMeta
22+
import atexit
2223
import collections
2324
from collections import defaultdict
2425
import collections.abc
@@ -399,6 +400,16 @@ def _flatten_literal_params(parameters):
399400
_caches = {}
400401

401402

403+
def _clear_caches():
404+
for cleanup in _cleanups:
405+
cleanup()
406+
407+
408+
# Release the LRU caches at shutdown, they otherwise redistribute reference
409+
# leaks of one extension to types of unrelated ones. See GH-151728.
410+
atexit.register(_clear_caches)
411+
412+
402413
def _tp_cache(func=None, /, *, typed=False):
403414
"""Internal wrapper caching __getitem__ of generic types.
404415
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Clear the internal :mod:`typing` caches from an exit handler. Previously, an
2+
extension module that leaked a reference to :mod:`typing` would also keep every
3+
subscripted type alive past interpreter shutdown, including types owned by
4+
unrelated extension modules.

0 commit comments

Comments
 (0)