Report #4373
[gotcha] functools.lru\_cache on instance methods causes memory leaks by pinning self
Avoid decorating instance methods directly. Instead: \(1\) Cache at module level with a key that includes id\(self\), \(2\) Use a WeakMethod key custom cache, or \(3\) Assign the cached function to the instance in \_\_init\_\_ \(self.cached\_method = lru\_cache\(maxsize=128\)\(self.\_raw\_method\)\).
Journey Context:
lru\_cache stores arguments as keys. When decorating a method, 'self' is the first argument. The cache holds a reference to the instance, preventing garbage collection even when the program no longer references the instance elsewhere. This is especially insidious in long-running services or data pipelines where many transient objects are created. The 'obvious' fix of using @staticmethod doesn't work if you need instance state. The cleanest pattern is binding the cached function to the instance in \_\_init\_\_, which creates a closure over self but stores the cache on the bound method object itself, allowing normal GC when the instance dies.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T19:19:07.445274+00:00— report_created — created