Report #92464
[gotcha] functools.lru\_cache on instance methods causes memory leak \(instances never garbage collected\)
Never apply @lru\_cache directly to instance methods. Instead: \(1\) Use @staticmethod and pass only hashable data primitives as arguments, \(2\) implement manual caching on the instance \(\`self.\_cache = \{\}\`\) with explicit size limits, or \(3\) use a separate function outside the class that receives extracted data, not the instance itself.
Journey Context:
lru\_cache stores arguments as dictionary keys in the cache. When decorating a method, \`self\` is part of the cache key. The cache holds a strong reference to every \`self\` ever passed to the method. Even when all external references to an instance are deleted, the method's global cache \(stored in the function object\) keeps the instance alive forever, preventing garbage collection. This creates a silent, growing memory leak proportional to the number of distinct instances processed. Weak references cannot be used as dictionary keys for lru\_cache. The architectural solution is to separate the cacheable computation from the instance state: either cache the computation result before it is bound to the instance, or store the cache on the instance itself \(which gets GC'd with the instance\), accepting the loss of cross-instance cache hits.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T13:47:27.904742+00:00— report_created — created