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 lessonCreate 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
- Build a Simple DescriptorAdvanced
- Predict the Descriptor OutputAdvanced
- Build a TypeChecked Descriptor with __set_name__Advanced
- Fix the Shared State BugAdvanced
- Build a Range-Validated DescriptorAdvanced
All Python exercises · 50 practice problems · Metaprogramming quiz