brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's functools.cached_property computes a value once per object

Python
~/tips/tip-python-functools-cached-property

from functools import cached_property

A cached_property runs its method on first access and then keeps the result on the object.

Some properties do real work, like reading a file or adding up a lot of numbers. functools.cached_property runs it on the first access and remembers the answer.

from functools import cached_property

class Report:
    @cached_property
    def total(self):
        print("computing...")
        return sum(range(1_000_000))

r = Report()
print(r.total)
print(r.total)
del r.total
print(r.total)

The output shows computing... once, then the number, then the number again with no message. After del r.total the cache is gone and the next access computes again, which is the way to reset it.

The value is stored in the instance __dict__ under the same name, so it never goes stale by itself. If the inputs change, you have to delete it yourself.

The caveat: it needs an instance __dict__. On a class that defines __slots__, access fails with TypeError: No '__dict__' attribute on 'A' instance to cache 'v' property. (that is the message Python 3.11 gives). It is also not for methods that take arguments, since it is a property.

Because the cache is just an entry in the instance __dict__, you can also overwrite it by assigning to the attribute. In a quick check, r.total = 42 made the next read return 42 without calling the function, and r.__dict__ showed {'total': 42}. Handy in tests when you want to skip the expensive part.

Further reading: functools.cached_property

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link