functools | Python Standard Library – Real Python

The Python functools module provides higher-order functions and tools for working with callable objects.

This module allows you to work with functions in a functional programming style, offering utilities that modify or extend the behavior of functions and methods in Python.

Here’s an example:

>>> import functools

>>> double = functools.partial(lambda x, y: x * y, x=2)
>>> double(5)
10

Key Features

  • Provides tools for creating partial functions
  • Supports function memoization with lru_cache
  • Offers decorators for method caching
  • Includes utilities for comparing and ordering

Frequently Used Classes and Functions

Examples

Create a partial function that computes powers of 3:

>>> from functools import partial

>>> cube = partial(lambda x, y: x**y, y=3)
>>> cube(4)
64

Use reduce() to compute the product of a list:

>>> from functools import reduce
>>> reduce(lambda x, y: x * y, [1, 2, 3, 4])
24

Common Use Cases

  • Creating functions with fixed arguments for repeated use
  • Optimizing recursive functions with caching
  • Transforming comparison functions for sorting
  • Performing cumulative operations on data collections

Real-World Example

Suppose you have a recursive function that calculates Fibonacci numbers, and you want to optimize it by using caching to avoid redundant calculations:

>>> from functools import lru_cache

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

>>> fibonacci(100)
354224848179261915075

Here, the @lru_cache decorator significantly improves the performance of the Fibonacci function by storing the results of previously computed values, avoiding the need to recompute them.

For additional information on related topics, take a look at the following resources: