This rule raises an issue when an instance method takes no parameter besides the instance and is decorated with functools.lru_cache or functools.cache.

It raises an issue only when the Python version of the analyzed project is 3.12 or later.

Why is this an issue?

functools.lru_cache and functools.cache store results on the function, and the key includes self. The instance references its class, the class references the cached function, and the cache references the instance. That cycle is anchored on the class. Reference counting does not free it, and the cyclic garbage collector does not either, because the class can still reach the instance.

A method with no other parameter has one result per instance. functools.cached_property stores that result on the instance itself. When the caller drops the instance, the cached value is dropped with it.

cached_property has existed since Python 3.8. Python 3.12 removed its undocumented lock. This rule applies only when the project targets Python 3.12 or later.

Exceptions

Do not raise when the project targets a Python version older than 3.12.

Do not raise when the method takes any parameter besides the instance, including defaults, keyword-only parameters, *args or **kwargs. {rule:python:S9156} covers that case.

Do not raise on async methods. cached_property does not await a coroutine.

Do not raise on @staticmethod or @classmethod methods, or on methods of enum.Enum subclasses.

How to fix it

Replace @lru_cache or @cache with @cached_property, and read the value as an attribute (obj.total instead of obj.total()).

Code examples

Noncompliant code example

from functools import lru_cache

class Series:
    def __init__(self, n: int) -> None:
        self.n = n

    @lru_cache  # Noncompliant: the cache retains "self"
    def fib(self) -> int:
        # long computation
        a, b = 0, 1
        for _ in range(self.n):
            a, b = b, a + b
        return a

Compliant solution

from functools import cached_property

class Series:
    def __init__(self, n: int) -> None:
        self.n = n

    @cached_property
    def fib(self) -> int:
        # long computation
        a, b = 0, 1
        for _ in range(self.n):
            a, b = b, a + b
        return a

Resources

Documentation

Related rules