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?
p.x += 1already works to producep.xequaling7with your current code (demo). Please clarify what you actually want._xattribute while making the cached propertyxrecalculated the next time it is read, in which case I don't think your analogy is a fitting one.