Functional Utilities with `functools`
Standard Library
functools Playbook
functools supercharges functions: cache expensive calls, build partials, and preserve metadata for decorators.
Caching with lru_cache and cache
from functools import lru_cache, cache
@lru_cache(maxsize=256)
def get_exchange_rate(code: str) -> float:
...
@cache # Python 3.9+, unbounded — simpler than lru_cache(maxsize=None)
def fibonacci(n: int) -> int:
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
- Use
@cache(Python 3.9+) for simple unbounded memoization. - Use
@lru_cache(maxsize=N)when you need to limit memory. cache_info()shows hit/miss stats.
Partials & wraps
from functools import partial, wraps
send_sales_email = partial(send_email, template='sales')
def measure(func):
@wraps(func)
def wrapper(*args, **kwargs):
...
return wrapper
partialpre-fills arguments for reuse.wrapskeeps metadata intact when writing decorators.
reduce & total_ordering
functools.reduceperforms cumulative operations; prefer built-ins likesumwhen possible.@functools.total_orderingfills in comparison methods when you implement__eq__and one ordering method.