pythonbeginner
functools.cache and lru_cache
Memoize expensive function calls with functools.cache and lru_cache for automatic result caching.
pythonPress ⌘/Ctrl + Shift + C to copy
from functools import cache, lru_cache
# Unlimited cache (Python 3.9+)
@cache
def fibonacci(n: int) -> int:
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
# LRU cache with max size
@lru_cache(maxsize=256)
def fetch_config(key: str) -> dict:
# Simulated expensive lookup
configs = {
"db": {"host": "localhost", "port": 5432},
"cache": {"host": "localhost", "port": 6379},
}
return configs.get(key, {})
# Cache info
print(fibonacci(100))
print(fibonacci.cache_info())
# Clear cache
fetch_config.cache_clear()Use Cases
- Recursive algorithms
- API response caching
- Expensive computations
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
Memoize Functions with lru_cache
Cache expensive function results automatically using functools.lru_cache.
Best for: Recursive algorithms
#python#caching
typescriptintermediate
In-Memory Caching with LRU Strategy
Implement LRU cache with TTL expiration, size limits, and cache-aside pattern for Node.js applications.
Best for: API response caching
#nodejs#caching
typescriptintermediate
ETag Caching Middleware
Express middleware that generates ETags and handles 304 Not Modified responses for bandwidth savings.
Best for: API caching
#express#caching
typescriptadvanced
Caching Strategies in Next.js
Master Next.js caching with fetch cache, unstable_cache, revalidatePath, and revalidateTag patterns.
Best for: ISR page caching
#nextjs#caching