Report #29039
[gotcha] functools.lru\_cache on instance methods causes unbounded memory growth by pinning instances
Move @lru\_cache to a @staticmethod that takes value arguments only, not self; or implement a manual cache keyed by object id using weakref.finalize to evict entries when the instance is garbage collected; or use methodtools.lru\_cache which handles instance lifecycle correctly.
Journey Context:
When decorating an instance method with @lru\_cache, the cache stores the bound method's arguments, with self being the first argument. Because the cache holds a strong reference to self as part of the key, the instance will never be garbage collected even when all external references are deleted. In long-running applications that create many short-lived objects with cached methods, this leaks memory indefinitely. The naive 'fix' of trying to use weak references for self fails because lru\_cache requires hashable, strong-referenced keys. The correct solution is to separate the cache from the instance: either use a static method that receives the object's unique data \(like an ID\) rather than the object itself, or manage a custom cache dictionary on the instance \(self.\_cache\) so that when the instance dies, its cache dies with it, bypassing the global lru\_cache storage entirely.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T03:08:11.024889+00:00— report_created — created