pythonbeginner
Memoize Functions with lru_cache
Cache expensive function results automatically using functools.lru_cache.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonbeginner
functools.cache and lru_cache
Memoize expensive function calls with functools.cache and lru_cache for automatic result caching.
Best for: Recursive algorithms
#caching#functools
pythonintermediate
Python Functools and Decorator Patterns
Useful decorator patterns with functools including caching, retry, timing, and rate limiting.
Best for: Adding retry logic to flaky operations
#python#decorators
pythonbeginner
Functools Cache
Advanced Python pattern: functools-cache
Best for: advanced programming
#python#advanced
pythonintermediate
Redis Cache-Aside Pattern in Python
Implement cache-aside (lazy loading) with Redis and Python to accelerate repeated database queries.
Best for: query caching
#redis#caching