8. Caching data and results

Use the lru_cache decorator to cache the results of pure or repeatable functions, especially when they are expensive to call. The first call still does the work, but repeated calls with the same arguments can be much faster.

The main readability win is that the cache policy lives on the function instead of being reimplemented in calling code. It works best when the function is deterministic for a given input and the cached results are reasonably reusable.

8.1. Don’t do this

1def add(n):
2    return sum([i for i in range(n)])
3
4add(10000000)

8.2. Do this

1from functools import lru_cache
2
3@lru_cache(maxsize=32)
4def add(n):
5    return sum([i for i in range(n)])
6
7add(10000000)