Sub topic 13
cached_property and non-data descriptors
This chapter assumes you know how obj.name is resolved. That means the data versus non-data descriptor rules, the instance __dict__, and __set_name__. It uses those rules to explain functools.cached_property. This one feature shows why the "non-data" half of the descriptor split exists.
What cached_property does
cached_property turns a method into an attribute that is computed on first access and then stored on the instance.
from functools import cached_property
class Dataset:
def __init__(self, values):
self.values = values
@cached_property
def total(self):
print("computing total")
return sum(self.values)
d = Dataset([1, 2, 3])
print("total" in d.__dict__) # False
print(d.total) # prints "computing total", then 6
print("total" in d.__dict__) # True
print(d.total) # 6, with no "computing total" lineAfter the first access, total is an ordinary entry in d.__dict__. Later reads do not call your function. They find the stored value through normal instance lookup.
Why a non-data descriptor makes this work
cached_property defines __get__ and __set_name__. It does not define __set__ or __delete__, so it is a non-data descriptor. The lookup order from the earlier chapters then gives this behavior:
- On the first access,
d.__dict__has nototalentry. Lookup falls through to the class attribute. That attribute is a non-data descriptor, so Python calls its__get__. __get__runs your function and writes the result intod.__dict__["total"].- On the second access, the instance
__dict__is checked before any non-data descriptor. It containstotal, so that value is returned and__get__is never called.
The cache is the instance dictionary, and the shadowing rule decides when it is used.
A minimal implementation
Writing the mechanism yourself makes the rule concrete.
class lazy:
def __init__(self, func):
self.func = func
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
value = self.func(obj)
obj.__dict__[self.name] = value
return value
class Report:
calls = 0
@lazy
def summary(self):
Report.calls += 1
return "summary text"
r = Report()
print(r.summary, r.summary, r.summary) # summary text three times
print(Report.calls) # 1
print(Report.summary) # the lazy object, from the obj is None branchThree details matter here:
__set_name__records the attribute name, so the descriptor knows which key to write in the instance__dict__.obj is Nonemeans the access came through the class, as inReport.summary. Returningselflets you inspect the descriptor instead of raising an error.- The value is stored under the same name as the descriptor. A non-data descriptor makes that safe, because the instance entry shadows it.
What breaks if you add `__set__`
Adding __set__ makes the descriptor a data descriptor. Data descriptors take precedence over the instance __dict__, so the stored value is never read.
class BrokenLazy(lazy):
def __set__(self, obj, value):
obj.__dict__[self.name] = value
class Report2:
calls = 0
@BrokenLazy
def summary(self):
Report2.calls += 1
return "summary text"
r2 = Report2()
r2.summary
r2.summary
r2.summary
print(Report2.calls) # 3
print("summary" in r2.__dict__) # True, but it is ignoredThe value is in r2.__dict__, but lookup checks the class first and finds a data descriptor. It calls __get__ every time, and the function runs on every access. This is the main reason cached_property cannot be built on property.
Invalidating and overriding the cache
The cache is a normal instance attribute, so ordinary attribute operations control it.
d = Dataset([1, 2, 3])
print(d.total) # computing total, then 6
d.values.append(10)
print(d.total) # 6, stale because the cache does not track inputs
del d.total # removes the entry from d.__dict__
print(d.total) # computing total, then 16
d.total = 99 # plain assignment writes d.__dict__["total"]
print(d.total) # 99del d.totalworks because there is no__delete__on the descriptor. Python falls back to deleting the entry from the instance__dict__. If nothing is cached yet, it raisesAttributeError.d.total = 99works because there is no__set__. Assignment goes to the instance__dict__and shadows the descriptor. Apropertywithout a setter would raiseAttributeErrorhere.- The cache does not know when
valueschanges. You must invalidate it yourself withdel.
A common pattern is a method that resets several cached values at once:
class Dataset2(Dataset):
def reset(self):
self.__dict__.pop("total", None)property compared with cached_property
| Aspect | `property` | `functools.cached_property` |
|---|---|---|
| Descriptor kind | Data (`__get__`, `__set__`, `__delete__`) | Non-data (`__get__` only) |
| Function runs | On every read | Once per instance, until the entry is deleted |
| Where the value lives | Computed on demand | Instance `__dict__`, under the same name |
| Assignment | Calls the setter, or raises `AttributeError` if none | Overwrites the cache |
| Works with `__slots__` | Yes | No, unless `__dict__` is a slot |
| Best for | Cheap or always-fresh values, validated setters | Expensive values that rarely change |
Failure modes
No instance `__dict__`
The cache needs somewhere to write. A class that defines __slots__ without __dict__ has no instance dictionary, so the first access fails.
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)
try:
Slotted([1, 2]).total
except TypeError as exc:
print("TypeError:", exc)Use a plain property, or add "__dict__" to __slots__. Adding __dict__ gives up some of the memory savings that motivated slots.
The same descriptor under two names
cached_property remembers the single name it was given in __set_name__. If you assign one instance to a second name, as in alias = total, access through the second name raises TypeError. The stored key would be wrong otherwise, so it refuses.
Concurrency
Two threads can both miss the cache and both run the function. In Python 3.8 through 3.11, cached_property took a lock around the computation. The lock was shared across all instances of that property, which could serialize unrelated work. Python 3.12 removed it. On current versions the function may run more than once under a race. The last writer wins, which is harmless for pure functions. If the function has side effects, add your own locking.
Stale values and mutable inputs
The cache holds whatever the function returned at the time. Mutating the inputs afterwards, as the append example above showed, leaves the old value in place. If the answer depends on mutable state, a property is the safer choice.
Class-level access
Dataset.total calls __get__ with obj set to None. cached_property returns the descriptor itself, which is why help(Dataset) and documentation tools can list it.
Choosing between them
- Use
cached_propertywhen the computation is expensive, the result stays valid for the object's life, and the class has an instance__dict__. - Use
propertywhen the value must always reflect current state, when you need validation on assignment, or when the class uses__slots__. - Write a custom non-data descriptor, as in
lazy, only when you need behaviorcached_propertylacks, such as a different cache key or an invalidation hook.
Exercise
A class defines @cached_property def config(self), and the function prints "loading" each time it runs. You run x = Settings(); x.config; x.config; del x.config; x.config; x.config = "manual"; x.config. How many times is "loading" printed, and why?
Show answer
Twice. The first x.config finds nothing in x.__dict__, so __get__ runs the function (1) and stores the result. The second read is served from x.__dict__. del x.config removes that entry, so the next read runs the function again (2). Assigning "manual" writes directly to x.__dict__ because the descriptor has no __set__, and the final read returns "manual" without calling the function.
Exercise
You write a custom caching descriptor that stores the computed value in obj.__dict__[self.name], but you also define __set__ so that assignment is validated. The function now runs on every access. Explain why, and name one way to fix it.
Show answer
Defining __set__ makes the descriptor a data descriptor, so it takes precedence over the instance __dict__. Lookup never reaches the cached entry and calls __get__ every time. One fix is to remove __set__ so the descriptor is non-data. Another is to keep __set__ and have __get__ check its own private storage, such as obj.__dict__["_" + self.name], before computing. That works because the cache key differs from the descriptor's public name.