Compute Once, Read Many Times? Python's cached_property and Its Limits

This article explains how functools.cached_property computes an attribute on first access and stores it in the instance, how its value is overridden and invalidated, and why stale data, threads since Python 3.12 and __slots__ limit its use.

A bright green snake with white patches resting in folded coils over a branch, its head tucked against its body
Photo by Antonio Janeski on Unsplash

An attribute that is expensive to compute, such as a statistic over a large dataset or a parsed configuration, poses a choice between computing it in __init__, even when it is never used, and computing it on every access, as a property does. The present article addresses functools.cached_property, available since Python 3.8, which computes the value on the first access and stores it in the instance, so that every later access is an ordinary attribute read. It measures the gain, explains how the cached value is overridden and invalidated, and analyses the limits that the documentation states explicitly: stale values, concurrent threads since Python 3.12, and classes without an instance dictionary. Paying for an expensive attribute only once, and only if it is ever read, is the secret weapon of cached_property.

Computing Once, on First Access

The decorator turns a method into an attribute whose first read calls the method and writes the result into the instance dictionary under the same name. From then on the dictionary entry is found before the decorator is consulted, a precedence rule examined in the article devoted to descriptors, so the method never runs again for that instance. Unlike a property, which rejects assignments unless it defines a setter, a cached property accepts writes, and deleting the attribute clears the cache so that the next read computes the value again.

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)

data = Dataset([1, 2, 3])
print(data.total, data.total)
data.total = 100
print(data.total, "total" in vars(data))
del data.total
print(data.total)
# Output: computing
# Output: 6 6
# Output: 100 True
# Output: computing
# Output: 6

The first two reads trigger a single computation, the assignment replaces the cached value like any attribute, and the deletion removes it, so the following read calls the method again. The same pattern of computing on the first request and serving the stored result afterwards appears in mappings, as described in the article devoted to __missing__; cached_property applies it to a single attribute of each instance.

Stale Values and Invalidation

Some role-playing games display a character sheet whose statistics are calculated when the sheet is opened and are not refreshed while it stays open, even if the character equips a new item in the meantime. This means that a cached property reflects the state of the instance at the moment of its first read, and nothing in the decorator detects that the data behind it changed afterwards. The analogy, however, stops at this point, because closing and reopening the sheet refreshes it, whereas a cached property is refreshed only when the program deletes the attribute explicitly.

from functools import cached_property

class Dataset:
    def __init__(self, values):
        self.values = values

    @cached_property
    def total(self):
        return sum(self.values)

    def add(self, value):
        self.values.append(value)
        self.__dict__.pop("total", None)

data = Dataset([1, 2, 3])
print(data.total)         # Output: 6
data.values.append(4)
print(data.total)         # Output: 6
data.add(5)
print(data.total)         # Output: 15

The direct append leaves the total at 6 although the list now sums to 10, while the method add updates the list and discards the cached value in one step, so the next read is correct. Removing the key with pop on __dict__ avoids the AttributeError that del raises when the value has not been computed yet. The documentation accordingly recommends the decorator for instances that are "otherwise effectively immutable"; for data that change often, a plain property remains the correct choice.

Pitfalls of cached_property

The decorator relies on the instance dictionary and on the absence of concurrent first reads, so its errors appear when either assumption fails. Six pitfalls are distinguished, which are the following:

  1. Stale values. The cache does not observe the data it was computed from, so every mutation must invalidate it.
  2. Concurrent first reads. Since Python 3.12 the decorator has no lock, so several threads may run the method for the same instance.
  3. Classes without __dict__. Classes whose __slots__ omit __dict__, and metaclasses, cannot use the decorator, and the first read raises TypeError.
  4. Memory per instance. The documentation notes that the decorator interferes with key-sharing dictionaries, so instance dictionaries may grow.
  5. Accidental overrides. Because the attribute accepts writes, an assignment silently replaces the computed value.
  6. lru_cache on methods instead. Decorating a method with lru_cache keeps every instance alive in the cache, a cost described in the article devoted to lru_cache.

The second and third pitfalls are reproduced in the following example.

import threading
import time
from functools import cached_property

calls = 0

class Slow:
    @cached_property
    def value(self):
        global calls
        calls += 1
        time.sleep(0.05)
        return 42

shared = Slow()
threads = [threading.Thread(target=lambda: shared.value) for _ in range(5)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()
print(calls)  # Output: 5

class Slotted:
    __slots__ = ("x",)

    @cached_property
    def y(self):
        return 1

try:
    Slotted().y
except TypeError as error:
    print(error)  # Output: No '__dict__' attribute on 'Slotted' instance to cache 'y' property.

Five threads read the attribute before any of them stored it, so the method ran five times; before Python 3.12 an undocumented per-property lock prevented this, at the price of contention between unrelated instances. When the method is expensive or has side effects, the documentation recommends locking inside the method or around the access. The slotted class fails on the first read because there is no dictionary in which to store the value.

Choosing How to Provide a Computed Attribute

Consequently, the decorator suits expensive values of instances that do not change after creation, and the measured gain is large: on CPython 3.12, a property that summed a thousand numbers took about 7 microseconds per read, while a cached read took about 26 nanoseconds. The following table summarizes the alternatives.

Situation Recommended approach
A cheap value, or data that change often property
An expensive value of an effectively immutable instance functools.cached_property
The value is always needed Compute it in __init__
Data that change through known methods cached_property invalidated in those methods
First reads from several threads A lock inside the method, or computation before sharing
Classes with __slots__ and no __dict__ property over an explicit slot, or property stacked on lru_cache
Caching results of functions rather than attributes functools.cache or lru_cache

Conclusion

It is concluded that cached_property computes an attribute on its first read and stores it in the instance dictionary, that later writes override it and deletion invalidates it, and that the gain over a property reaches orders of magnitude for expensive values. This magic holds only while the instance does not change, while first reads do not race, which since Python 3.12 is the responsibility of the program, and while the class has an instance dictionary. Describing the methods that an object must offer, so that any class providing them is accepted without inheriting from a common base, is the purpose of typing.Protocol, which is developed in a future article of this series.