Report #88477
[gotcha] Memory leak when using functools.lru\_cache on instance methods
Never apply @lru\_cache directly to instance methods; instead refactor as @staticmethod or a module-level function, or use WeakKeyDictionary for per-instance caching
Journey Context:
lru\_cache caches by argument identity, so when decorating an instance method, 'self' becomes part of the cache key. This pins every instance ever passed to the method in memory, preventing garbage collection. Increasing maxsize makes it worse. Common wrong fixes: using 'self.\_\_dict\_\_' as cache \(unhashable\), or ignoring the leak. Correct alternatives: move logic to a @staticmethod so 'self' isn't cached, cache on a WeakKeyDictionary keyed by id\(self\) with weak references, or compute outside the class entirely.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T07:05:21.133904+00:00— report_created — created