Skip to main content

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
  • partial pre-fills arguments for reuse.
  • wraps keeps metadata intact when writing decorators.

reduce & total_ordering

  • functools.reduce performs cumulative operations; prefer built-ins like sum when possible.
  • @functools.total_ordering fills in comparison methods when you implement __eq__ and one ordering method.

Next up in your learning path