Report #71871
[gotcha] Memory leak when applying functools.lru\_cache to instance methods
Never apply @lru\_cache directly to instance methods. Instead, refactor to a @staticmethod that takes explicit parameters, or implement a custom cache using weakref.WeakMethod to avoid pinning self in the cache indefinitely.
Journey Context:
The lru\_cache decorator stores results in a dict keyed by arguments. When decorating a bound method, 'self' becomes part of the key. Since each instance has a unique identity, the cache grows linearly with instance count, leaking memory as instances go out of scope but remain cached. Developers incorrectly assume the cache is per-class or global; they try \_\_slots\_\_ \(irrelevant\) or manual clearing \(brittle\). WeakMethod-based caches are complex. The correct pattern is to cache at the function level with lightweight hashable arguments, not heavy self references.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T03:12:52.514878+00:00— report_created — created