Lab 09: JIT & Caching Patterns
Overview
Step 1: functools.lru_cache Internals
functools.lru_cache Internalsimport functools
import sys
@functools.lru_cache(maxsize=128)
def fib(n: int) -> int:
if n < 2:
return n
return fib(n-1) + fib(n-2)
# Compute and inspect cache
result = fib(30)
print(f"fib(30) = {result}")
info = fib.cache_info()
print(f"Cache info:")
print(f" hits={info.hits}, misses={info.misses}")
print(f" maxsize={info.maxsize}, currsize={info.currsize}")
print(f" hit rate: {info.hits/(info.hits+info.misses)*100:.1f}%")
# __wrapped__ gives access to the unwrapped function
unwrapped = fib.__wrapped__
print(f"\nfib.__wrapped__ is fib: {unwrapped is fib}")
print(f"fib.__wrapped__(5) = {unwrapped(5)}") # No caching, recursive call
# Clear and recompute
fib.cache_clear()
info_after = fib.cache_info()
print(f"\nAfter cache_clear: {info_after}")Step 2: functools.cache — Unbounded Cache
functools.cache — Unbounded CacheStep 3: Understanding Cache Key Generation
Step 4: Custom TTL Cache Decorator
Step 5: Method Caching with cached_property
cached_propertyStep 6: Memoization with Disk Cache (joblib pattern)
Step 7: Caching with numpy — Ufunc Caching
Step 8: Capstone — Production Cache Layer
Summary
Concept
API
Use Case
Last updated
