A plain fib(30) makes 2,692,537 calls because it repeats the same work. With functools.cache every answer is computed once and the count drops to 31 (Python 3.9+).
python3 --version.python3 -m venv .venv source .venv/bin/activate
python3 fib.py
from functools import cache # Python 3.9+
def fib(n):
global calls; calls += 1
return n if n < 2 else fib(n-1) + fib(n-2)
calls = 0; fib(30); print(calls)
fib = cache(fib); calls = 0; fib(30); print(calls)This function repeats the same work millions of times. Each call splits in two, and counts itself. Run it plain, then wrapped in functools cache. Each answer computed once, then remembered.
2.7 million calls, down to 31. Repeated work? Cache it.
Read the lesson on GitHub →