Hard: Advanced Interview · Problem 77 of 82

Write memoize

HardDecorators and AdvancedPython

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)?

  1. args only
  2. (args, tuple(sorted(kwargs.items())))
  3. kwargs only

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?

  1. It does not
  2. The name fib inside the function refers to the decorated version, which checks the cache
  3. 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.)