I can cache an instance attribute like so:
from dataclasses import dataclass
from functools import cached_property
@dataclass
class Point:
_x: float
@cached_property
def x(self):
return self._x * 2
>> p = Point(3)
>> p.x
6
I want to have the calculation applied to x
every time I call it, using a cached result for subsequent calls to avoid unnecessary computations.
But I also want to change x
. While p.x += 1
works with the code above, many places say that @cached_property
is meant for immutable values. And in my actual, more complex code, it gives me strange, inscrutable results. I chalked this up to surprising behaviour when the decorator is used with mutable attributes (even though I don’t fully understand what’s happening).
What’s the proper way to cache an instance attribute that changes throughout its lifetime?
5
@cached_property
is mainly intended for properties that should be considered immutable. The documentation specifically says:
Useful for expensive computed properties of instances that are otherwise effectively immutable.
However, it also mentions that you can clear the cache by deleting the attribute. So you can do:
del p.x
p._x = 5
print(p.x) # this will print 10
2