Deviopath › Python

Memoize with Stats

Hard · Decorators

A memoize decorator remembers results, so calling a slow function again with the same arguments is instant. A good decorator also uses functools.wraps(func) on its wrapper: it copies __name__ and __doc__ from the original function, so tracebacks and tools still see the real name.

Write a decorator memoize(func):

- cache results by the positional arguments (they are always hashable here)

- the returned function has two attributes: calls (how many times it was called) and misses (how many of those calls actually ran func)

- keep the name and docstring of func

The driver run_memoize(args_list) is already written. It decorates an area(w, h) function, calls it once per [w, h] pair, and returns the results, your two counters, how many times area really ran, and its name and docstring.

Next: Retry Decorator with Arguments