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
from functools import lru_cache
@lru_cache(maxsize=256)
def get_exchange_rate(code: str) -> float:
...
- Perfect for I/O-bound operations or expensive calculations.
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.