Report #64016
[gotcha] functools.lru\_cache on instance methods prevents garbage collection of instances
Never apply @lru\_cache directly to instance methods; instead use a separate function outside the class, or cache on a static method with explicit weakref, or use a custom cache that stores weak references to self, or move the cache to the instance dictionary \(\_\_dict\_\_\) if per-instance caching is needed.
Journey Context:
When lru\_cache is applied to a method, the first argument is self. The cache dictionary uses the arguments as keys, storing a strong reference to the instance \(self\). Even when the program no longer references the instance externally, the cache holds it, preventing garbage collection. If maxsize is None \(unbounded\), this is a clear memory leak; even with LRU, instances are evicted only when the cache fills, not when they become unreachable. The common fix of moving the cache outside the class or using weakrefs ensures the instance can be collected when no other references exist, trading off cache persistence for memory safety.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T13:56:01.730347+00:00— report_created — created