Python 3.8+functoolsterm
functools.cached_property
caching
Computes the value of a property once and stores it in the instance's __dict__. Later accesses return the cached value without calling the method.
Syntax
@functools.cached_property
The cache never invalidates itself: if the object's fields change, the property keeps returning the stale value until you delete it with del obj.area. It needs a normal instance __dict__, so a class with __slots__ will not work — there is nowhere to store the value. Since Python 3.12 there is no shared lock, so under threads the computation may run more than once.
Examples
from functools import cached_property
class Circle:
def __init__(self, r): self.r = r
@cached_property
def area(self):
return 3.14159 * self.r ** 2
c = Circle(5)
print(c.area) # → 78.53975
print(c.area) # → 78.53975 (без вычисления)
print('area' in c.__dict__) # → True
print(type(c.__dict__['area'])) # → <class 'float'>
See also
Open in the full glossarydocs.python.orgReport an inaccuracy