Memoization & Caching with @functools.lru_cache
`@functools.lru_cache(maxsize=128)` caches function return values keyed by arguments. Repeated calls with identical arguments return in $O(1)$ time from RAM ⚡.
import functools
@functools.lru_cache(maxsize=128)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(50)) # Instantaneous calculation ⚡
print(fib.cache_info()) # hits, misses, maxsize, currsize 📊
# 40. Memoization & Caching with @functools.lru_cache `@functools.lru_cache(maxsize=128)` caches function return values keyed by arguments. Repeated calls with identical arguments return in $O(1)$ time from RAM ⚡. ```python import functools @functools.lru_cache(maxsize=128) def fib(n): if n < 2: return n return fib(n - 1) + fib(n - 2) print(fib(50)) # Instantaneous calculation ⚡ print(fib.cache_info()) # hits, misses, maxsize, currsize 📊 ``` LRU stands for Least Recently Used. When the cache hits `maxsize`, Python automatically evicts the oldest untouched entry to prevent RAM leaks! ⚡ --- ### Question What does LRU stand for in `@functools.lru_cache`? 🧠 - [ ] a. Least Recently Used (evicts oldest untouched items when full) ⚡ - [ ] b. Linear Resource Unification - [ ] c. Low Latency Routing Utility - [ ] d. Logical Register Unpacker --- ### Challenge Import `functools`. Apply `@functools.lru_cache(maxsize=32)` to `def square(n): return n * n`. Call `square(4)` twice. Print `square.cache_info().hits`. 🎯 <details> <summary>Solution</summary> ```python import functools @functools.lru_cache(maxsize=32) def square(n): return n * n square(4) square(4) print(square.cache_info().hits) ``` </details>