Report #8588
[gotcha] functools.lru\_cache on methods caches the instance \(self\) preventing garbage collection
Use \`weakref.WeakMethod\` as a custom key, or move the cache to the class level with a WeakKeyDictionary keyed by instance id, or ensure \`maxsize\` is small and instances are long-lived. Alternatively, use \`methodtools.lru\_cache\` \(3rd party\) which handles weak references correctly.
Journey Context:
When \`@lru\_cache\` decorates a method, the \`self\` argument becomes part of the cache key. The cache \(a dict\) holds a reference to the instance. Even when the caller deletes all external references to the object, the cache keeps it alive, leaking memory. This is especially bad with \`maxsize=None\` on frequently created temporary objects. Common 'fix' of clearing cache in \`\_\_del\_\_\` is impossible because \`\_\_del\_\_\` won't run while cache holds reference \(circular\). The robust solution uses \`weakref.WeakKeyDictionary\` at class level to map instance -> cached result, allowing GC when instance dies, or using 3rd party libs that implement this pattern.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T05:49:54.059768+00:00— report_created — created