Memoizing previous results with lru_cache
The lru_cache
decorator transforms a given function into a function that might perform more quickly. The LRU means Least Recently Used—a finite pool of recently used items is retained. Items not frequently used are discarded to keep the pool to a bounded size.
Since this is a decorator, we can apply it 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 calculation. Because of this decoration, each call to the fibc(n)
function will now be checked against a cache maintained by the decorator. If the argument n
is in the cache, the previously computed result is used instead of doing a potentially expensive re-calculation. Each...