snippetpythonModeratepending
Python functools recipes: lru_cache, partial, reduce
Viewed 0 times
lru_cachecachepartialreducememoizationfunctools
Problem
Need memoization, partial application, and other functional programming utilities in Python.
Solution
Essential functools patterns:
from functools import lru_cache, cache, partial, reduce, wraps
# Memoization with lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
# Unlimited cache (Python 3.9+)
@cache
def expensive_lookup(key):
return database.query(key)
# Check cache stats
print(fibonacci.cache_info())
# CacheInfo(hits=46, misses=50, maxsize=128, currsize=50)
fibonacci.cache_clear() # Reset cache
# Partial application
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5)) # 25
# Partial with logging
import logging
debug = partial(print, '[DEBUG]')
warn = partial(print, '[WARN]', flush=True)
# Reduce for accumulation
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda acc, x: acc + x, numbers, 0) # 15
# Compose functions
def compose(*funcs):
return reduce(lambda f, g: lambda x: f(g(x)), funcs)
process = compose(str.upper, str.strip, str.lower)
print(process(' Hello ')) # 'HELLO'Why
functools provides optimized implementations of common functional patterns. lru_cache alone can dramatically speed up recursive or repetitive computations.
Gotchas
- lru_cache arguments must be hashable (no lists/dicts)
- cache has no size limit - can cause memory issues
- lru_cache on instance methods caches per-instance (use __hash__)
Context
Python code needing caching, partial application, or functional patterns
Revisions (0)
No revisions yet.