0Pricing
Python Academy · Lesson

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))  # instant

All lessons in this course

  1. itertools: Infinite and Finite Iterators
  2. itertools: Combinatorics
  3. functools: partial and reduce
  4. functools: lru_cache and cached_property
← Back to Python Academy