Skip to content

Use WeakKeyDictionary in decorators.cached #1781

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -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?
=============================
Expand Down
5 changes: 4 additions & 1 deletion astroid/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import inspect
import sys
import warnings
import weakref
from collections.abc import Callable
from typing import TypeVar

Expand All @@ -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:
Expand Down