10.2 Memoizing previous results with cache
The @cache
and @lru_cache
decorators transform a given function into a function that might perform more quickly. LRU means Least Recently Used—a finite pool of recently used items is retained. Items not recently used are discarded to keep the pool to a bounded size. The @cache
has no storage management and requires a little bit of consideration to be sure it won’t consume all available memory.
Since these are decorators, we can apply one of them to any function that might benefit from caching previous results. We can use it as follows:
from functools import lru_cache
@lru_cache(128)
def fibc(n: int) -> int:
if n == 0: return 0
if n == 1: return 1
return fibc(n-1) + fibc(n-2)
This is an example based on Chapter 6, Recursions and Reductions. We’ve applied the @lru_cache
decorator to the naive Fibonacci number...