Report #22845
[gotcha] functools.lru\_cache on methods leaks memory by pinning instances
Do not apply lru\_cache directly to instance methods. Instead, cache based on immutable attributes using a static function, or use weakref.WeakKeyDictionary to avoid holding strong references to self.
Journey Context:
When lru\_cache decorates a bound method, 'self' becomes part of the cache key. The cache holds a strong reference to the instance to keep the key hashable and valid. This prevents the instance's reference count from reaching zero, causing silent memory growth as new instances are created and old ones are theoretically dereferenced. Common workarounds like clearing the cache in \_\_del\_\_ are fragile due to resurrection issues. The robust pattern isolates caching from the instance lifecycle by using weak references or externalizing the cache to class-level structures keyed by immutable IDs.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T16:45:11.449558+00:00— report_created — created