pythonbeginner

Memoize Functions with lru_cache

Cache expensive function results automatically using functools.lru_cache.

python
from functools import lru_cache
import time

@lru_cache(maxsize=128)
def fibonacci(n: int) -> int:
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

# Without cache: exponential time
# With cache: linear time
start = time.perf_counter()
result = fibonacci(100)
print(f"fib(100) = {result}")
print(f"Time: {time.perf_counter() - start:.6f}s")

# Check cache stats
print(fibonacci.cache_info())
# CacheInfo(hits=98, misses=101, maxsize=128, currsize=101)

# Clear cache if needed
fibonacci.cache_clear()

Use Cases

  • Recursive algorithms
  • Expensive computations
  • API response caching

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.