PY-CACH0002 · cached_instance_method
Avoid retaining object instances in function-wide method caches.
This is a deterministic rule for python. Read its implementation.
Definition
Section titled “Definition”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.
Evidence
Section titled “Evidence”Each finding identifies the class, method, cache decorator, and complete source range. The Boolean result identifies one cached instance method.
Exceptions
Section titled “Exceptions”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.
Examples
Section titled “Examples”@lru_cache(maxsize=128)def parse(self, text: str) -> Node: return self.parser.parse(text)@cached_propertydef schema(self) -> Schema: return build_schema(self.fields)
@cachedef tokenizer(model: str) -> Tokenizer: return Tokenizer.load(model)References
Section titled “References”- Cites “The Python Standard Library”, functools.lru_cache. Open reference
- Cites “Python FAQ”, caching methods. Open reference