Skip to content

PY-CACH0002 · cached_instance_method

Avoid retaining object instances in function-wide method caches.

This is a deterministic rule for python. Read its implementation.

Inspect direct class methods decorated with functools.cache or functools.lru_cache, including called decorator forms and qualified names. Report ordinary instance methods, which are the ones binding neither classmethod nor staticmethod, because Python includes self in the cache key and retains cached arguments until eviction or an explicit clear. Use cached_property for a zero-argument value owned by one instance. Move a computation independent of instance identity to a module-level cached function.

Each finding identifies the class, method, cache decorator, and complete source range. The Boolean result identifies one cached instance method.

Static methods and class methods are excluded because they do not retain ordinary instances. Generated and vendored code can be excluded by path. A deliberately bounded instance cache may disable this preference when its ownership and clearing behavior are explicit.

@lru_cache(maxsize=128)
def parse(self, text: str) -> Node:
return self.parser.parse(text)
@cached_property
def schema(self) -> Schema:
return build_schema(self.fields)
@cache
def tokenizer(model: str) -> Tokenizer:
return Tokenizer.load(model)