How to Build Partial Functions with functools.partial in Python
Create reusable partial functions that pre-fill arguments using functools.partial, like making square and cube functions from a general power function.
Python code
16 lines```python
from functools import partial
def power(base, exponent):
"""Calculate base raised to the exponent power."""
return base ** exponent
# Create partial functions for common powers
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
if __name__ == "__main__":
squares = [square(x) for x in range(1, 6)]
cubes = [cube(x) for x in range(1, 6)]
print(f"Squares: {squares}")
print(f"Cubes: {cubes}")
Output
Squares: [1, 4, 9, 16, 25]
Cubes: [1, 8, 27, 64, 125]
How it works
functools.partial returns a new callable that behaves like the original function but with some arguments already fixed. By passing exponent=2 as a keyword argument, the partial function square only needs the base argument when called. The original power function remains unchanged, so you can still call it with both arguments. This pattern reduces code duplication when you repeatedly call a function with the same fixed arguments. The __main__ guard ensures the example code only runs when the script is executed directly.
Common mistakes
- Passing positional arguments to partial when keyword arguments would be clearer
- Trying to override an already-fixed argument in the partial call
- Forgetting that partial creates a new function object, not a modified original
Variations
- Use `lambda` for simple cases: `square = lambda x: power(x, 2)`
- Define dedicated functions manually: `def square(x): return power(x, 2)`
Real-world use cases
- Creating a customized HTTP request handler that always sends the same headers or base URL with requests.get.
- Building a logging helper that pre-fills a logger name and level for repeated logging calls in one module.
- Adapting a generic sorting key function with a fixed column index for reusable dataframe or list sorting operations.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.