Editor

Build a Cached Property Descriptor

Advanced · Write the code · from Python Descriptors: The Secret Behind @property and ORM Fields

From the lesson: Python Descriptors: The Secret Behind @property and ORM Fields

When you use @property in Python, something interesting happens behind the scenes. The attribute doesn't just sit there waiting to be read - it intercepts access and runs custom code. How does that work?

Read the lesson

Create a non-data descriptor called CachedProperty that works as a decorator. It should:

1. Compute the value by calling the decorated function on first access

2. Store the result in the instance's __dict__ so it's only computed once

3. Use __set_name__ to learn the attribute name

Use it in a Stats class:

class Stats:
    def __init__(self, numbers):
        self.numbers = numbers
    
    @CachedProperty
    def total(self):
        print('computing')
        return sum(self.numbers)

Create Stats([10, 20, 30]), access total twice, and print the result both times.

class CachedProperty:
# Your code here
pass
class Stats:
def __init__(self, numbers):
self.numbers = numbers
@CachedProperty
def total(self):
print('computing')
return sum(self.numbers)
s = Stats([10, 20, 30])
print(s.total)
print(s.total)

More Descriptor exercises

All Python exercises · 50 practice problems · Metaprogramming quiz