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 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
  • 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