Report #39504
[gotcha] functools.lru\_cache on methods leaks memory by caching bound method instances
Move cache to class level with explicit key including instance id, or use \`weakref.WeakMethod\` to allow garbage collection, or implement \`\_\_slots\_\_\` to prevent \_\_dict\_\_ bloat from cached bound methods
Journey Context:
When lru\_cache decorates an instance method, it caches the bound method object \(self \+ function\). The cache key includes the arguments, but the value stored is the bound method itself, which holds a strong reference to the instance. Even when all external references to the instance are dropped, the lru\_cache keeps the instance alive forever, causing a memory leak. This is insidious because the cache appears to work correctly but leaks memory in long-running processes. The obvious fix of \`self.method = lru\_cache\(maxsize=128\)\(self.method\)\` doesn't work because it still binds. The correct approaches are to cache at the class level with explicit instance in the key, use WeakMethod to allow GC when the instance dies, or avoid caching methods entirely.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T20:46:44.417510+00:00— report_created — created