Function caching with `functools.cache` [ref]
Problem
- Cache a recursive Fibonacci function and evaluate it for
10.
- Call a cached function twice with argument
4 and count body executions.
- Cache a decomposition returning a tuple rather than a mutable list.
- Try calling a cached function with a list argument and catch the hashability error.
Python solution
from functools import cache
@cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
fib(10) # 55
calls = []
@cache
def square(x):
calls.append(x)
return x * x
square(4) # 16
square(4) # 16
calls # [4]
@cache
def suffix(i):
return () if i == 2 else ("x", *suffix(i + 1))
suffix(0) # ('x', 'x')
try:
fib([1])
except TypeError:
unhashable = True
unhashable # True
Links