Python
@cached_property
Learn cached properties with @cached_property.
@cached_property
@cached_property comes from the functools module and is the cached version of @property. The computation runs once, the result is stored in the instance dictionary; later reads come straight from the cache.
Example: an expensive area computation @cached_property\ndef area(self):\n return self.w * self.h. The first read computes, the second returns from cache. If the attribute is deleted (del obj.area) the cache is cleared and the next read recomputes.
When to use it?
@cached_property is ideal for expensive, unchanging computations. Example: line count from a file, a complex math result or a sum over a large list. If the computation does not change after the first run on the same instance, the cache stays correct.
If the instance changes the cache goes stale; in that case you can delete it from __dict__ to recompute. It pairs well with frozen dataclasses; for example coordinate types.
Exercise cached_property for Rectangle
Start with from functools import cached_property. Define a Rectangle class; def __init__(self, w, h): and in the body write self.w = w, self.h = h. Add a method def area(self): with @cached_property, body return self.w * self.h. After the class create r = Rectangle(4, 5) and print with print(r.area).
Show example solution
# Write the Rectangle class with @cached_property
from functools import cached_property
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
@cached_property
def area(self):
return self.w * self.h
r = Rectangle(4, 5)
print(r.area)
Test yourself
-
Match the property types
- @property
- Computes every time
- @cached_property
- Computes once, then caches
- del obj.area
- Clears the cache
- functools
- Module
-
When does @cached_property refresh the cache?
- On every call
- When the attribute is deleted
- Only when the program starts
- When the class is defined
Show answer
When the attribute is deleted — Deleting the attribute clears the cache and the next read recomputes.
-
cached_property import line
from functools import ____
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
Show answer
from functools import cached_property
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
Next lesson: functools.wraps