Sub topic 11
Caching expensive values with cached_property
This chapter assumes you can write @property getters and setters, and that you know instance attributes live in obj.__dict__. You should also be able to read a basic decorator. The chapter covers what functools.cached_property does, how it works, where its cache goes stale, and when to pick it over a plain property.
The problem: a property that recomputes every time
A computed property runs its method on every read. That is fine for fahrenheit, which is one multiplication. It is wasteful when the method does real work, such as summing a million numbers, parsing a file, or querying a database.
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 again, then 6You could store the result yourself in an attribute such as _total and check it for None on each read. That works, but it is boilerplate you repeat for every cached value. functools.cached_property does the same job.
Using cached_property
Import it from functools and use it where you would use @property.
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 instance
print(d.__dict__) # {'values': [1, 2, 3], 'total': 6}Three points to notice:
- The method runs once per instance, not once per class. Two
Datasetobjects each compute their own total. - Callers use the same syntax as for a property:
d.total, with no parentheses. - The result appears in
d.__dict__under the nametotal. That detail explains the rest of the behavior.
How it works internally
property is a data descriptor. It defines __set__, so Python always calls it, even when the instance dictionary has a key with the same name. cached_property defines only __get__ and __set_name__. That makes it a non-data descriptor, and Python gives non-data descriptors lower priority than the instance dictionary.
The lookup for d.total goes like this:
- First read:
d.__dict__has nototal, so Python callscached_property.__get__. __get__runs your method and writes the result intod.__dict__["total"].- Later reads: Python finds
totalin the instance dictionary and returns it. The descriptor is never called again.
__set_name__ is how the descriptor learns the attribute name (total) it should use as the dictionary key. This is the same hook the Positive descriptor used in the descriptors chapter.
Invalidating the cache
Because the cache is an ordinary instance attribute, you can delete it. The next read recomputes the value.
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) # computing, then 6
d.values.append(4)
print(d.total) # 6 (stale: the list changed but the cache did not)
del d.total # removes 'total' from d.__dict__
print(d.total) # computing, then 10The second print shows the main risk. cached_property does not watch its inputs. If anything the method depends on changes, the cached value stays wrong until you remove it.
A common fix is to clear the cache from the setter of the attribute it depends on.
from functools import cached_property
class Dataset:
def __init__(self, values):
self.values = values # runs the setter
@property
def values(self):
return self._values
@values.setter
def values(self, new_values):
self._values = list(new_values)
self.__dict__.pop("total", None) # drop any cached total
@cached_property
def total(self):
return sum(self._values)
d = Dataset([1, 2, 3])
print(d.total) # 6
d.values = [10, 20] # setter clears the cache
print(d.total) # 30pop("total", None) is used instead of del because the cache may not exist yet. During __init__ it never does. The setter also copies the list. This stops callers from mutating the stored list behind your back, which would bypass the setter.
Gotchas
It is not read-only
A property without a setter rejects assignment. A cached_property has no __set__, so assignment succeeds and overwrites the cache.
d = Dataset([1, 2, 3])
d.total = 999 # no error: writes 999 into d.__dict__
print(d.total) # 999If callers must not overwrite the value, use a plain @property and cache by hand, or accept that the value can be replaced.
It needs an instance `__dict__`
Classes that declare __slots__ without "__dict__" have nowhere to store the result. Reading the attribute raises TypeError.
from functools import cached_property
class Slotted:
__slots__ = ("values",)
def __init__(self, values):
self.values = values
@cached_property
def total(self):
return sum(self.values)
s = Slotted([1, 2])
try:
s.total
except TypeError:
print("cannot cache without __dict__")One name per descriptor
The descriptor stores the result under the name it received in __set_name__. Assigning the same cached_property object to a second name in the class body raises TypeError, because it would write to the wrong key.
Thread safety depends on the Python version
Before Python 3.12, cached_property held a lock shared by all instances of the descriptor. That prevented the method from running twice in a race, but it also made unrelated instances wait on each other. Python 3.12 removed the lock. Now two threads that read at the same moment may both run the method, and the last write wins. If the method has side effects or must run exactly once, add your own lock.
Do not cache methods with `lru_cache`
functools.lru_cache on a method keeps a reference to self in its cache. That keeps every instance alive for as long as the cache holds them. For a zero-argument computed value per instance, cached_property avoids that problem.
Choosing between the options
| Situation | Best choice |
|---|---|
| Cheap to compute, inputs may change | `@property` |
| Expensive, inputs never change after construction | `@cached_property` |
| Expensive, inputs change through a known setter | `@cached_property` plus cache clearing in the setter |
| Must reject assignment | `@property` with no setter |
| Class uses `__slots__` | `@property` with a manual cache slot |
| Method takes arguments | `functools.lru_cache`, with care about instance lifetime |
Summary of behavior
cached_propertyruns the method on first read and stores the result in the instance__dict__under the same name.- It works because it is a non-data descriptor, and the instance dictionary takes priority over it.
del obj.nameclears the cache. Clear it from setters when the inputs can change.- It does not block assignment, does not work without
__dict__, and has version-dependent locking.
Exercise
A class Report has a cached_property named summary that reads self.rows, a list attribute. A caller runs r.summary, then runs r.rows.append(row), then runs r.summary again. The second result does not include the new row. Explain why, and give one way to make the next read of summary correct.
Show answer
The first read stored the result in r.__dict__["summary"]. On the second read Python finds that key in the instance dictionary and returns it, so the method never runs again. cached_property does not track changes to self.rows. To fix it, run del r.summary (or r.__dict__.pop("summary", None)) after changing rows, so the next read recomputes. A more durable fix is to make rows a property whose setter clears the cache, and to expose an add_row method that also clears it, so callers do not mutate the list directly.
Exercise
Why does d.total = 999 succeed on a cached_property but c.radius = 5 raise AttributeError on a getter-only @property?
Show answer
property defines __set__, so it is a data descriptor and handles every assignment. With no setter function it raises AttributeError. cached_property defines no __set__, so assignment goes to the instance dictionary and replaces the cached value.