This rule raises an issue when an instance method is decorated with functools.lru_cache or functools.cache and the method
takes parameters besides the instance.
functools.lru_cache and functools.cache store results on the function. The cache key includes every argument. On an
instance method, that key includes self.
The decorated function is stored on the class, and the class stays loaded for the whole process. Each cache entry holds a strong reference to
self, so the instance and the objects it references stay in memory until the cache drops the entry.
@cache and @lru_cache(maxsize=None) never drop entries, so each cached instance leaks until the process exits. A bounded
@lru_cache drops an entry only after newer calls fill the cache. Once the entry is dropped, nothing else keeps the instance alive, and
reference counting frees it immediately.
Keeping the same function at module level does not help if it still receives the instance. The fix is to keep self out of the cache
key. A cached function that receives only plain values, such as scale and n, does not keep the instance alive.
@lru_cache drops that entry once newer calls fill the
cache.@cache and @lru_cache(maxsize=None) never drop entries, so memory grows with the number of cached instances.Do not raise when the method takes no parameter besides the instance, on every Python version. On Python 3.12 and later, {rule:python:S9453}
recommends functools.cached_property for that case. On earlier versions this rule stays silent for that case.
Do not raise on @staticmethod or @classmethod methods. The cache does not retain a per-instance self.
Do not raise on methods of enum.Enum subclasses. Enum members are singletons, so retaining them is bounded.
Move the cache to a free function that takes the values required for the computation, then call that function from the method. self is
not an argument of the cached function, so the cache does not keep the instance alive.
from functools import lru_cache
class Series:
def __init__(self, scale: int) -> None:
self.scale = scale
@lru_cache # Noncompliant: the cache retains "self"
def fib(self, n: int) -> int:
# long computation
if n < 2:
return n
return self.scale * (self.fib(n - 1) + self.fib(n - 2))
from functools import lru_cache
@lru_cache
def fib(scale: int, n: int) -> int:
# long computation
if n < 2:
return n
return scale * (fib(scale, n - 1) + fib(scale, n - 2))
class Series:
def __init__(self, scale: int) -> None:
self.scale = scale
def fib(self, n: int) -> int:
return fib(self.scale, n)
functools.lru_cachefunctools.cache