Report #12749
[gotcha] Memory leak using @functools.lru\_cache on instance methods
Never apply @lru\_cache directly to methods. Move logic to a standalone function \(explicit self argument\), or use per-instance caching via \_\_dict\_\_ or weakref.WeakKeyDictionary.
Journey Context:
@lru\_cache stores results in a dict attached to the function object. When decorating a method, the function object is shared across all instances. The cache key includes all arguments; because bound methods prepend self automatically, every call from a different instance creates a unique cache key containing that instance object. This causes unbounded cache growth \(one entry per instance\) and prevents garbage collection of instances because the function's cache holds strong references to every self ever passed. This leak is invisible in standard profiling because the retained memory is in the class's function object, not instance \_\_dict\_\_. The architectural fix requires breaking the shared cache: either move the function outside the class \(so self becomes an explicit argument in the cache key, but you control what gets cached\), or use per-instance storage where the cache dies with the instance.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T16:50:04.226169+00:00— report_created — created