functools: lru_cache and cached_property
Cache expensive computations with lru_cache and cached_property.
What Is Memoization?
Memoization caches the result of a function call keyed by its arguments. Repeated calls with the same arguments return the cached result instantly.
def slow_fib(n):
if n < 2: return n
return slow_fib(n-1) + slow_fib(n-2)
# slow_fib(35) makes ~29 million calls
# With caching it makes only 35@lru_cache
@functools.lru_cache(maxsize=128) caches up to maxsize recent results. Set maxsize=None for an unbounded cache.
import functools
@functools.lru_cache(maxsize=None)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)
print(fib(50)) # instantAll lessons in this course
- itertools: Infinite and Finite Iterators
- itertools: Combinatorics
- functools: partial and reduce
- functools: lru_cache and cached_property