CodeBlanks Logo Icon CodeBlanks

@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.

Practice 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).

Starter code

main.py
# Write the Rectangle class with @cached_property

Sample solution

main.py
# 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)

Expected output

20

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the property types

Term Meaning
@property Computes every time
@cached_property Computes once, then caches
del obj.area Clears the cache
functools Module

2 When does @cached_property refresh the cache?

  • On every call
  • When the attribute is deleted Correct answer
  • Only when the program starts
  • When the class is defined

Explanation: Deleting the attribute clears the cache and the next read recomputes.

3 cached_property import line

Question
from functools import ____

class Rectangle:
    def __init__(self, w, h):
        self.w = w
        self.h = h
Answer
from functools import cached_property

class Rectangle:
    def __init__(self, w, h):
        self.w = w
        self.h = h

Explanation: cached_property is imported from the functools module.

All lessons in Intermediate