Report #82563
[gotcha] Memory leak when applying @lru\_cache to instance methods because cache holds reference to self
Do not decorate instance methods with @lru\_cache. Instead, refactor to a cached static method or module-level function that takes the instance's hashable state \(not self\) as an argument. If caching must be per-instance, initialize a dict cache in \_\_init\_\_ \(self.\_cache = \{\}\) and manage manually, or use weakref.WeakMethod to avoid strong reference cycles.
Journey Context:
@lru\_cache stores results in a dict keyed by the hash of the function arguments. When decorating an instance method, 'self' is the first argument and becomes part of the cache key. The cache \(stored on the function object itself, effectively a global cache\) holds a strong reference to every instance ever passed to that method, preventing garbage collection until the cache entry is evicted or the cache is cleared. Since caches are stored on the function object \(class attribute\), they persist for the process lifetime. Developers assume @lru\_cache is 'safe' for methods like it is for functions, but it creates a hidden global registry of all instances, causing memory leaks in long-running services.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T21:10:21.176619+00:00— report_created — created