17. Memoize a Function
Difficulty: Medium · Topic: Functions & decorators
Write a decorator memoize that caches results: when the decorated function is called again with the same arguments, return the stored result without running the function.
- Arguments are hashable. Keyword arguments count:
price(100, tax=5)is cached separately fromprice(100, tax=10). - Results such as
None,0or''are cached too. - Each decorated function has its own cache, and keeps its
__name__.
In the sample, slow_square(4) runs once and the second call comes from the cache, so the function runs only twice in all: len(calls) is 2.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
calls = []
@memoize
def slow_square(x):
calls.append(x)
return x * x
[slow_square(4), slow_square(4), slow_square(5), len(calls)]Expected: [16, 16, 25, 2]
Hints
Hint 1
Keep a dict in the decorator's closure, keyed by the arguments.Hint 2
A key that includes keyword arguments:(args, tuple(sorted(kwargs.items()))).Hint 3
Test membership withkey in cache, not by the cached value being truthy.Learn the concepts
- Decorators · 8 min read. What @ does, wrappers for any function, functools.wraps, and decorators with arguments.
More Python problems
- Counter with a Closure · Easy
- A Logging Decorator That Keeps Metadata · Easy
- Time Every Call · Medium
- Retry with Backoff · Hard
- Rate Limiter Decorator · Hard