Use functools tools to cache, adapt, dispatch, and wrap Python callables.
What You Will Learn
functools provides utilities for higher-order functions and decorators. Common applications are memoization with cache or lru_cache, partial argument binding, decorator metadata preservation with wraps, and generic dispatch with singledispatch.
Caching is appropriate only when a callable result is reusable for equivalent arguments.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from functools import partial, reduce
multiply_by_four = partial(lambda left, right: left * right, 4)
print(multiply_by_four(6))
print(reduce(lambda left, right: left + right, [1, 2, 3], 0))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: functools.
- The variable multiply_by_four holds the result of partial(lambda left, right: left * right, 4). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
24
6
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Turn a two-argument formatter into a specialized callable using partial().
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming every functools decorator is pure or thread-safe just because it is in the standard library.
- Using a wrapper without checking which original function, arguments and return values it preserves.
Key Takeaways
- Use functools tools to cache, adapt, dispatch, and wrap Python callables.
- functools provides utilities for higher-order functions and decorators.
- Caching is appropriate only when a callable result is reusable for equivalent arguments.