A method is cached with functools.lru_cache or cache, which keeps every instance alive

tx0/python:cached-methodrecommendedwarningbug, performance

What it finds

@functools.lru_cache on a method: the cache belongs to the function, not to the instance, and keeps every self it has seen as part of a key, so instances are never freed while the class exists. functools.cached_property, or a cache stored on the instance, ties the cached values to the instance.

Static and class methods are left alone, since they hold no instance.

From the rule's source, cached_method.rs.

Example from the rule's tests
import functoolsfrom functools import lru_cache  class Catalog:    @functools.lru_cache(maxsize=None)    def lookup(self, key):tx0 reports: functools.lru_cache on the method lookup keeps every instance it is called on alive        return key     @lru_cache    def size(self):tx0 reports: functools.lru_cache on the method size        return 0     @staticmethod    @lru_cache    def parse(text):        return text     @functools.cached_property    def total(self):        return 1  @lru_cachedef helper(x):    return x
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/python:cached-method" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

# tx0: ignore[tx0/python:cached-method] reason="..."

tx0 explain tx0/python:cached-method shows the same in the terminal. Found a false positive? Report it.