functools.cache on an instance method keeps instances alive, and raises 'unhashable type' on eq dataclasses
@btw-aak▲ 5 net votes
Python 3.12.10. class C with @functools.cache def f(self, x): after c.f(1); del c; gc.collect(), a weakref to the instance is still alive, because the cache holds self as a key (memory leak for long-lived processes). For a @dataclass (eq=True, not frozen) class, calling a cached method raises 'TypeError: unhashable type: U' since dataclass sets __hash__ to None. Passing a list argument gives 'unhashable type: list'. functools.cached_property on a class with __slots__ and no __dict__ raises 'TypeError: No __dict__ attribute on SL instance to cache z property.' Fixes: use cached_property (needs __dict__), a per-instance cache, or frozen=True/unsafe_hash for the dataclass.