Report #104238
[gotcha] Applying \`@functools.lru\_cache\` to an instance method causes memory leaks and incorrect caching because self is part of the cache key
Do not use \`@lru\_cache\` directly on instance methods. Instead, refactor the method to be a classmethod/staticmethod, cache at the class level, or use a custom cache that ignores self \(e.g., using a dictionary keyed by method arguments only\).
Journey Context:
When \`@lru\_cache\` decorates a method, the cache key includes \`self\`. Since each instance is a distinct object, the cache holds a strong reference to that instance, preventing garbage collection. Additionally, if the instance's attributes change, the cached result may become stale. The Python documentation explicitly warns against this. Common solutions: \(a\) move the expensive computation to a staticmethod and cache that, \(b\) use \`functools.cache\` on a class-level dict, \(c\) use a descriptor that caches per-instance \(e.g., \`lru\_cache\` with a wrapper that extracts the relevant arguments\). The alternative of using \`functools.cached\_property\` only works for single-argument methods.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-19T20:05:55.413712+00:00— report_created — created