Sub topic 13
cached_property and non-data descriptors
This chapter assumes you know the descriptor protocol, the difference between data and non-data descriptors, and the lookup order where a data descriptor beats the instance __dict__ and the instance __dict__ beats a non-data descriptor.
The idea
functools.cached_property computes a value on first access and stores it on the instance. Later reads return the stored value without calling your function again.
It does this with no special interpreter support. It is a non-data descriptor: it defines __get__ but not __set__ or __delete__. That means an entry in the instance __dict__ shadows it. The first read runs __get__, which writes the result into the instance __dict__ under the same name. Every later read finds that entry first, so the descriptor is never consulted again.
A minimal implementation
This version shows the whole mechanism. It uses __set_name__ from the earlier chapters to learn its attribute name.
class my_cached_property:
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:
def __init__(self, rows):
self.rows = rows
@my_cached_property
def total(self):
print("computing")
return sum(self.rows)
r = Report([1, 2, 3])
print(r.total) # computing, then 6
print(r.total) # 6, with no "computing"
print("total" in r.__dict__) # TrueThe write goes to obj.__dict__ directly. Writing with setattr(obj, self.name, value) would also work here, because the descriptor has no __set__. Direct writes make the intent clearer.
Using the standard version
The standard library class works the same way, with extra checks.
from functools import cached_property
class Circle:
def __init__(self, r):
self.r = r
@cached_property
def area(self):
print("computing")
return self.r * self.r
c = Circle(2)
print(c.area) # computing, then 4
print(c.area) # 4
del c.area # removes the cached entry from the instance __dict__
c.r = 3
print(c.area) # computing, then 9Because there is no __delete__, del c.area falls through to the instance __dict__ and removes the cached value. This is the usual way to invalidate the cache. Assigning c.area = 100 also works, because there is no __set__, and it replaces the cached value.
Gotchas
- No instance
__dict__: a class that uses__slots__without a"__dict__"entry has nowhere to cache. Reading the attribute raisesTypeError. - Stale values: the cache does not notice changes to the data it was computed from. You must delete the entry yourself.
- Class access:
Circle.areareturns the descriptor object, because__get__receivesobj=None. - Name reuse: one
cached_propertyobject cannot be assigned to two different names.__set_name__raisesTypeError. - Threads: before Python 3.12,
cached_propertyheld a lock, so the function ran once per instance. From 3.12 the lock is gone, and two threads may both compute the value.
A property is a data descriptor, so it always runs your function. The only difference that matters here is the missing __set__.
Exercise
A class defines @cached_property def size(self). You run obj.size, then obj.__dict__["size"] = 99, then obj.size. What does the last read return, and why does the descriptor's __get__ not run?
Show answer
It returns 99. cached_property is a non-data descriptor, so an entry named size in the instance __dict__ takes precedence over it during lookup. Python finds that entry first and never calls __get__.
Exercise
Why does cached_property fail on a class that declares __slots__ = ("a",), and what is one way to fix it?
Show answer
The descriptor caches by writing into obj.__dict__, and a class with __slots__ and no "__dict__" slot has no instance dictionary. Adding "__dict__" to __slots__ fixes it. Another fix is to cache manually in a declared slot.