Skip to content

Commit 1ce6651

Browse files
committed
break potential reference cycles in external code worsened by typing.py lru_cache (#98253)
1 parent 75a6fad commit 1ce6651

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

Lib/typing.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -344,20 +344,23 @@ def _flatten_literal_params(parameters):
344344

345345

346346
_cleanups = []
347+
_caches = { }
347348

348349

349350
def _tp_cache(func=None, /, *, typed=False):
350351
"""Internal wrapper caching __getitem__ of generic types with a fallback to
351352
original function for non-hashable arguments.
352353
"""
353354
def decorator(func):
354-
cached = functools.lru_cache(typed=typed)(func)
355-
_cleanups.append(cached.cache_clear)
355+
cache = functools.lru_cache(typed=typed)(func)
356+
_caches[func] = cache
357+
_cleanups.append(cache.cache_clear)
358+
del cache
356359

357360
@functools.wraps(func)
358361
def inner(*args, **kwds):
359362
try:
360-
return cached(*args, **kwds)
363+
return _caches[func](*args, **kwds)
361364
except TypeError:
362365
pass # All real errors (not unhashable args) are raised below.
363366
return func(*args, **kwds)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed a source of potential type-related refleaks caused by LRU caches in
2+
``typing``.

0 commit comments

Comments
 (0)