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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

16 lines
Python 3.9+
```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

stdout
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

  1. Use `lambda` for simple cases: `square = lambda x: power(x, 2)`
  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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.