Editor

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 lesson

Write 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 25
from 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

All Python exercises · 50 practice problems · Advanced Python quiz