Report #9512
[gotcha] TypeError unhashable type in lru\_cache or memory leaks on instance methods
Never apply @lru\_cache to instance methods \(self is unhashable and leaks memory\). Use @functools.cached\_property for computed attributes, or move cache to instance \_\_dict\_\_ using WeakKeyDictionary for method-level caching. Convert lists/dicts to tuples/frozensets before passing to cached functions.
Journey Context:
lru\_cache uses dict hashing on arguments; unhashable types like list raise TypeError immediately. For methods, 'self' is passed as first argument, making the cache instance-specific but requiring the instance to be hashable \(rare for mutable objects\). Even when hashable, the cache is stored on the function object, not the instance, creating a reference cycle that prevents garbage collection of instances until the cache fills or the program exits. This causes severe memory leaks in long-running services. cached\_property stores the value on the instance \_\_dict\_\_, avoiding both the hashability requirement and the memory leak.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T08:20:26.158987+00:00— report_created — created