Report #102
[gotcha] @lru\_cache on a method leaks instances and breaks on unhashable arguments
Avoid @lru\_cache on instance methods; cache pure functions that take simple values instead. If you need per-instance caching, use functools.cached\_property \(read-only\) or manage a weakref-based cache. Ensure all arguments are hashable; convert lists/dicts to tuples/frozensets before calling a cached function.
Journey Context:
lru\_cache keys are built from the positional and keyword arguments passed to the decorated function. On a method, the first argument is self, so the cache holds a strong reference to every instance ever passed in, preventing garbage collection. Additionally, any mutable or unhashable argument \(list, dict, set\) immediately raises TypeError. Developers often solve this by wrapping arguments in tuple\(...\) inside the function, but that does not help because the cache sees the original unhashable object. The safe pattern is to keep @lru\_cache on free functions with hashable inputs and use @cached\_property for derived, immutable per-instance state.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-12T09:15:15.729877+00:00— report_created — created