logo

Partial Application with functools.partial

Sometimes you have a function with many arguments, but you want to fix some of them ahead of time. partial() creates a new function with those arguments pre-filled.

from functools import partial

def power(base, exponent):
    return base ** exponent

square = partial(power, exponent=2)
cube = partial(power, exponent=3)

print(square(5))  # 25
print(cube(5))    # 125

partial() returns a new callable that remembers the fixed arguments. You only supply the remaining ones.

This is useful for callbacks and functions passed to other functions:

# Instead of lambda x: power(x, 2)
numbers = [1, 2, 3, 4, 5]
list(map(partial(power, exponent=2), numbers))

Partial application makes your code more reusable without defining many small wrapper functions.

I cover partial and related tools in my Functional Programming course.