Report #5826
[gotcha] Decorating an instance method with \`@lru\_cache\` causes all instances to share the same cache, leaking memory via retained \`self\` references and polluting cache entries
Do not apply \`@lru\_cache\` directly to methods. Instead, \(1\) move the cached logic to a static method or module-level function, or \(2\) implement per-instance caching by assigning \`self.\_cache = functools.lru\_cache\(...\)\` in \`\_\_init\_\_\` and calling \`self.\_cache\(method\)\` inside the method, or \(3\) use a third-party library like \`methodtools.lru\_cache\` which handles the instance binding correctly.
Journey Context:
\`lru\_cache\` stores results in a dict attached to the function object. When you decorate a method defined in a class body, that function object is created once and shared by all instances. The \`self\` argument becomes part of the cache key, which is fine for correctness \(since different instances have different \`id\(self\)\`\), but means the cache grows with the number of instances and is never cleared even when instances are garbage collected \(the cache holds references to \`self\` via the key\). This causes memory leaks. Moreover, if \`\_\_hash\_\_\` or \`\_\_eq\_\_\` are overridden, \`self\` might not be hashable or might collide with other instances, breaking the cache entirely. The solution is to avoid decorating the method directly; instead, cache the underlying computation on a per-instance basis or outside the class.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T22:15:57.111400+00:00— report_created — created