Sub topic 11
Caching expensive values with cached_property
This chapter assumes you can write a class with @property, and that you know how instance attributes are stored in __dict__. You should also be comfortable with computed properties from the earlier chapter.
The problem: recomputing on every read
A computed property runs its function each time you read it. That is fine for fahrenheit, which is a single multiplication. It is wasteful when the value is expensive and does not change, such as the sum of a large list or the result of a database query.
class Dataset:
def __init__(self, values):
self.values = values
@property
def total(self):
print("computing")
return sum(self.values)
d = Dataset([1, 2, 3])
print(d.total) # computing, then 6
print(d.total) # computing, then 6 againThe sum is recalculated on both reads.
Using cached_property
functools.cached_property runs the method once per instance and keeps the result on that instance. Later reads return the stored value without calling the method.
from functools import cached_property
class Dataset:
def __init__(self, values):
self.values = values
@cached_property
def total(self):
print("computing")
return sum(self.values)
d = Dataset([1, 2, 3])
print(d.total) # prints "computing", then 6
print(d.total) # prints 6 only; the value was cached on the instanceHow it works
cached_property is a descriptor that has only a __get__ method. On the first read, Python finds the descriptor on the class, calls the method, and writes the result into the instance's __dict__ under the same name. On the next read, Python finds total in the instance __dict__ first and returns it. The descriptor is never reached.
Because the value is an ordinary instance attribute after the first read, you can check it directly:
d = Dataset([1, 2, 3])
print("total" in d.__dict__) # False
d.total
print("total" in d.__dict__) # TrueCommon errors
- Stale values. The cache is never refreshed on its own. If
d.valueschanges after the first read,d.totalkeeps the old result. - No setter protection. Since there is no
__set__, assigningd.total = 99simply overwrites the cached entry. It is not read-only the way a getter-onlypropertyis. - Missing
__dict__. The cache needs an instance__dict__. A class that defines__slots__without__dict__raisesTypeErroron first access. - Shared state assumptions. The cache is per instance. Two
Datasetobjects each compute their own total.
Invalidating the cache
Because the value lives in __dict__, del removes it. The next read recomputes it.
from functools import cached_property
class Dataset:
def __init__(self, values):
self.values = values
@cached_property
def total(self):
return sum(self.values)
d = Dataset([1, 2, 3])
print(d.total) # 6
d.values.append(4)
print(d.total) # 6, stale
del d.total
print(d.total) # 10Choosing between the options
| Need | Use |
|---|---|
| Cheap value derived from other attributes | `@property` |
| Expensive value, inputs fixed after creation | `@cached_property` |
| Validation on assignment | `@property` with a setter |
| Value stored once, never derived | Plain attribute |
Exercise
A class uses @cached_property for report. After the first read, you change an attribute that report depends on, and report still shows the old result. Give two ways to get a fresh value.
Show answer
Delete the cached entry with del obj.report, so the next read recomputes it. Alternatively, change the design so the value is not cached: switch to a regular @property, or make the inputs read-only so they cannot change after the first read.