Build a Simple Cache Decorator
Advanced · Write the code · from Python Decorators Explained: A Step-by-Step Guide
From the lesson: What Are the Most Useful Real-World Decorators?
Decorators shine in real-world applications. Here are three patterns you'll see constantly: timing, caching, and validation.
Read this part of the lessonWrite a decorator memoize that caches function results based on arguments. If the function is called with the same arguments again, return the cached result instead of calling the function.
Print 'Computing...' only when actually computing (not when returning cached results).
@memoize
def square(n):
print('Computing...')
return n ** 2
print(square(4)) # Computing... \n 16
print(square(4)) # 16 (cached!)
print(square(5)) # Computing... \n 25from functools import wraps
def memoize(func):
# Write your caching decorator here
pass
@memoize
def square(n):
print('Computing...')
return n ** 2
print(square(4))
print(square(4))
print(square(5))
More Decorator exercises
- Predict the Decorator OutputIntermediate
- Write a Logging DecoratorAdvanced
- Write a Repeat DecoratorAdvanced
- Predict Stacked Decorator OutputAdvanced
- Write a Validation DecoratorAdvanced
- Write a Retry DecoratorAdvanced
- Fix the Broken DecoratorIntermediate
All Python exercises · 50 practice problems · Advanced Python quiz