Write memoize
Write a decorator memoize that remembers the result of a function for each distinct set of arguments, so that calling it again with the same arguments does not run the function again.
- It must work with positional and keyword arguments. (All argument values are hashable.)
- The decorated function keeps its name.
- It must also work for a function that calls itself (recursion): the recursive calls use the cache.
Understand the problem
Decide what the cache key is.
Which value is a good dictionary key for the call f(1, 2, x=3)?
argsonly(args, tuple(sorted(kwargs.items())))kwargsonly
The key must contain everything that decides the result: the positional arguments and the keyword arguments. A dictionary is not hashable, so turn the keyword arguments into a tuple of (name, value) pairs, sorted so that their order does not matter.
For a recursive fib decorated with @memoize, why does the cache also speed up the inner calls?
- It does not
- The name
fibinside the function refers to the decorated version, which checks the cache - Python optimises recursion
After @memoize, the global name fib is the wrapper. When fib calls fib(n - 1), it calls the wrapper, which looks in the cache first. That is why decorating a recursive function with a cache turns it from exponential into linear.
Write the solution
Write the decorator.
def memoize(func):
# Write your code here.
pass
Hint 1: a question to ask yourself
Where do you keep the dictionary so that it lives as long as the decorated function does, and nobody else touches it?
Hint 2: the shape of the answer
A cache = {} in the outer function. In wrapper(*args, **kwargs), build the key, if it is not in the cache then compute and store, then return cache[key]. Use functools.wraps.
Reflect
Solution
import functools
def memoize(func):
cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
Another way: the standard library
import functools
def memoize(func):
return functools.wraps(func)(functools.cache(func))
What this tests: decorators with state, building a hashable key, dictionaries, recursion, and functools.cache.
Memoization requires purity. It is only correct for functions whose result depends only on their arguments and that have no side effects. A function that reads the clock or a file must not be cached like this.
Memory grows: an unbounded cache holds every result forever. functools.lru_cache(maxsize=1000) limits the size by evicting the least recently used entries (see the LRU Cache problem).
Unhashable arguments: a list argument cannot be a dictionary key, so f([1, 2]) would raise TypeError. The standard functools.cache has the same limit.
Use the library in real code: @functools.cache (Python 3.9+) or @functools.lru_cache.
What an interviewer might ask next: Add a cache_clear() function to the wrapper, as functools.lru_cache has. (wrapper.cache_clear = cache.clear.)
VISIBLE = 3
CASES = [
('calls = []\n@memoize\ndef sq(n):\n calls.append(n)\n return n * n\nsq(3)\nsq(3)\nsq(4)\nresult = calls', [3, 4], 'the function runs once per distinct argument'),
('@memoize\ndef fib(n):\n return n if n < 2 else fib(n - 1) + fib(n - 2)\nresult = fib(25)', 75025, 'a recursive function still gives the right answer'),
('calls = []\n@memoize\ndef f(a, b=0):\n calls.append(1)\n return a + b\nf(1, b=2)\nf(1, b=2)\nf(1, b=3)\nresult = (len(calls), f(1, b=2))', (2, 3), 'keyword arguments are part of the key'),
('calls = []\n@memoize\ndef f(a, b=0):\n calls.append(1)\n return a + b\nf(1, b=2)\nf(1, 2)\nresult = len(calls)', 2, 'f(1, b=2) and f(1, 2) are different calls'),
('@memoize\ndef f(x):\n """Doc."""\n return x\nresult = (f.__name__, f.__doc__)', ('f', 'Doc.'), 'name and docstring are kept'),
('calls = []\n@memoize\ndef f(x):\n calls.append(x)\n return None\nf(1)\nf(1)\nresult = len(calls)', 1, 'a result of None is cached too'),
('calls = []\n@memoize\ndef fib(n):\n calls.append(n)\n return n if n < 2 else fib(n - 1) + fib(n - 2)\nfib(30)\nresult = len(calls)', 31, 'each value is computed once'),
]