Report #14801
[gotcha] Memory leak when using functools.lru\_cache on instance methods
Avoid decorating instance methods directly with @lru\_cache. Instead, use a staticmethod pattern with explicit self managed via WeakKeyDictionary, or move the cache to the instance itself \(self.\_cache = \{\}\). Never let lru\_cache capture 'self' as part of the cache key on the function object.
Journey Context:
lru\_cache stores results in a dict keyed by function arguments. When decorating a method, the first argument is 'self' \(the instance\). The cache lives on the function object \(the descriptor\), not the instance. Consequently, every instance passed to the method creates a cache entry with that instance object as a key, which prevents the instance from being garbage collected even after the instance is no longer referenced elsewhere. This creates unbounded memory growth that is silent and difficult to diagnose. Staticmethod avoids the self parameter, while WeakKeyDictionary allows self to be garbage collected when the instance dies.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T22:25:37.751575+00:00— report_created — created