From a3e5320835f34bcc534b407f036878afcc0bc735 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Noord?= <13665637+DanielNoord@users.noreply.github.com> Date: Thu, 15 Sep 2022 11:09:04 +0200 Subject: [PATCH] Use ``WeakKeyDictionary`` in ``decorators.cached`` --- ChangeLog | 3 +++ astroid/decorators.py | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) 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: