diff --git a/ChangeLog b/ChangeLog index 142a9a7e0b..4c4ceb9c56 100644 --- a/ChangeLog +++ b/ChangeLog @@ -17,7 +17,10 @@ What's New in astroid 2.12.10? ============================== Release date: TBA +* ``decorators.cached`` now uses a ``WeakKeyDictionary`` to allow the garbave collector + to remove entries when possible. + Refs #1780 What's New in astroid 2.12.9? ============================= diff --git a/astroid/decorators.py b/astroid/decorators.py index c4f44dcd27..0a0ac48672 100644 --- a/astroid/decorators.py +++ b/astroid/decorators.py @@ -10,6 +10,7 @@ import inspect import sys import warnings +import weakref from collections.abc import Callable from typing import TypeVar @@ -32,8 +33,10 @@ def cached(func, instance, args, kwargs): """Simple decorator to cache result of method calls without args.""" cache = getattr(instance, "__cache", None) + # Use a WeakKeyDictionary to allow the garbage collector to remove entries + # that only exist in the cache. if cache is None: - instance.__cache = cache = {} + instance.__cache = cache = weakref.WeakKeyDictionary() try: return cache[func] except KeyError: