Glossary

Functools

The functools module provides higher-order functions and tools for working with callables. Its most commonly used features include @lru_cache (memoisation decorator that caches function results), @wraps (preserves metadata of wrapped functions), partial() (creates a new function with some arguments pre-filled), reduce() (applies a function cumulatively to a sequence), and @total_ordering (fills in missing comparison methods).

@functools.lru_cache(maxsize=128) is one of Python's most useful performance tools. It caches the results of expensive function calls and returns the cached result when the same arguments are seen again. It is particularly effective for recursive functions (like Fibonacci) and pure functions with repeated calls. Since Python 3.9, @functools.cache provides an unbounded cache with simpler syntax.

functools.partial(func, *args, **kwargs) creates a new callable with some arguments already supplied. For example, int_from_hex = functools.partial(int, base=16) creates a function that converts hexadecimal strings to integers. functools complements the itertools module: together they provide the core of Python's functional programming toolkit, enabling composition, memoisation, and higher-order function patterns.

Related terms: Itertools, Decorator, functools.wraps

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.