Content · Programming · Python

Python functools.cached_property() Decorator: Usage and Examples

Compute a read-only-style derived attribute once per instance.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Compute a read-only-style derived attribute once per instance.

What You Will Learn


cached_property stores the computed value in the instance __dict__ after the first access. It requires a writable instance dictionary, permits reassignment, and should not be assumed to calculate only once under concurrent access.

Caching uses extra memory and can return stale results when a function relies on changing state outside its arguments.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from functools import cached_property
class Invoice:
    def __init__(self, prices):
        self.prices = prices
    @cached_property
    def total(self):
        print('calculating')
        return sum(self.prices)
invoice = Invoice([5, 7])
print(invoice.total)
print(invoice.total)

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: functools.
  • The class Invoice groups data and behavior; its methods run when called on an instance.
  • The variable invoice holds the result of Invoice([5, 7]). Later lines use that value or inspect how it changes.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

calculating
12
12

When You Would Use This


These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.

Practice: Modify the Code


Delete an instance cached attribute and access it to force recalculation.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Using cached_property when the underlying data changes without invalidating the cached attribute.
  • Overlooking this documented constraint: it requires a writable instance dictionary, permits reassignment, and should not be assumed to calculate only once under concurrent access.

Key Takeaways


  • Compute a read-only-style derived attribute once per instance.
  • cached_property stores the computed value in the instance __dict__ after the first access.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.