SyntaxStudy
Sign Up
Python Intermediate 4 min read

functools Module

functools

functools provides higher-order function utilities: lru_cache, partial, reduce, and wraps.

Example
from functools import lru_cache, partial, reduce, wraps

@lru_cache(maxsize=256)
def fibonacci(n: int) -> int:
    if n < 2: return n
    return fibonacci(n-1) + fibonacci(n-2)

double = partial(lambda x, n: x * n, n=2)
total  = reduce(lambda a, b: a + b, [1, 2, 3, 4, 5])  # 15
def decorator(fn):
    @wraps(fn)     # preserves __name__, __doc__
    def wrapper(*args, **kw): return fn(*args, **kw)
    return wrapper
Pro Tip

Always use @wraps in decorators — without it, the wrapped function loses its identity for debugging.