functools Memoization: lru_cache & singledispatch
1Concept
`functools.lru_cache` provides high-performance Least-Recently-Used caching for pure functions. `functools.singledispatch` transforms a function into a generic function with polymorphic dispatch based on the type of the first argument.
2Architecture Diagram
lru_cache(maxsize=128): Input: fib(35) ---> Checks internal hash table ---> Instant O(1) Cache Hit!
3Code Example
Python 3.12
from functools import lru_cache, singledispatch
@lru_cache(maxsize=128)
def fib(n: int) -> int:
if n < 2: return n
return fib(n - 1) + fib(n - 2)
@singledispatch
def format_data(arg):
return f"Generic: {arg}"
@format_data.register
def _(arg: int):
return f"Integer Hex: 0x{arg:X}"
@format_data.register
def _(arg: list):
return f"List Length: {len(arg)}"
print(f"Fibonacci 30: {fib(30)}")
print(f"Cache Info: {fib.cache_info()}")
print(format_data(255))
print(format_data([1, 2, 3, 4]))4Expected Output
Fibonacci 30: 832040 Cache Info: CacheInfo(hits=28, misses=31, maxsize=128, currsize=31) Integer Hex: 0xFF List Length: 4
5Key Takeaways
- ✓Arguments to `@lru_cache` functions must be hashable.
- ✓`fib.cache_clear()` flushes the cache memory.
- ✓`@singledispatch` enables clean function polymorphism without giant `if isinstance(...)` trees.