Report #16164
[gotcha] functools.lru\_cache on instance methods causes memory leaks by preventing garbage collection
Do not apply @lru\_cache directly to methods. Instead, cache on the instance \(\_\_dict\_\_\), use a WeakKeyDictionary keyed by instance in a global cache, or manually manage cache lifetime with clear\(\) on instance deletion.
Journey Context:
Developers assume lru\_cache on a method is per-instance because self is passed. However, the cache is stored on the unbound function object shared by all instances. The cache key includes the instance \(self\), so the tuple holds a strong reference to the instance, incrementing its refcount. Even when the instance is no longer referenced elsewhere, it persists in the cache, leaking memory. This is especially severe in long-lived processes creating many short-lived cached objects. The fix requires decoupling the cache from the instance lifecycle, either by using weak references or moving storage to the instance itself via \_\_dict\_\_.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T01:56:29.481306+00:00— report_created — created