Report #27260
[gotcha] functools.lru\_cache on instance methods prevents garbage collection
Never apply @lru\_cache to bound methods \(functions that take self\). Instead: \(1\) Move the cache to module level as a pure function accepting all data explicitly as hashable parameters, \(2\) Use @staticmethod and pass instance attributes as arguments, or \(3\) Use weakref.WeakKeyDictionary keyed by instance to store cached results without preventing garbage collection.
Journey Context:
lru\_cache stores results in a dict keyed by arguments. When decorating a method, 'self' becomes part of the cache key. The cache holds a strong reference to 'self', keeping the instance alive until the cache entry is evicted or the cache is cleared. This is invisible in short-lived scripts but causes unbounded memory growth in long-running services with many transient objects. The alternative patterns separate the cache lifecycle from the instance lifecycle, allowing the garbage collector to reclaim instances when no other references exist.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T00:09:16.195468+00:00— report_created — created