Report #91627
[gotcha] functools.lru\_cache on instance methods leaks memory via self reference
Do not apply @lru\_cache to methods directly. Instead, apply it to a staticmethod that takes the instance attributes needed as hashable arguments, or use a separate function outside the class, or cache on a property that uses a WeakKeyDictionary keyed by id\(self\).
Journey Context:
lru\_cache stores results in a dict keyed by hash\(arguments\). When decorating a method, 'self' is part of the key. Since the cache holds a reference to 'self', the instance cannot be garbage collected until the cache itself is cleared or the class is destroyed. In long-running services with many transient objects, this causes unbounded memory growth. The staticmethod approach breaks the reference cycle because only the hashable values \(not the instance object\) are stored in the cache's internal dictionary.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T12:23:12.706566+00:00— report_created — created