Partial Functions in Python
Python Shorts — Part 8
Assume you have a function foo with a long argument list, and frequently use this in your code. It is tedious to always spell out the full call to foo — especially if some of the arguments are shared between calls. This is a common pattern: you might define a general, low-level function foo(a, b, c, d)— and then re-use this function from different modules A and B. From A you always call foo(A1, A2, A3, x), and from B foo(B1, B2, B3, y). In these cases, or whenever you want to simplify and encapsulate usage of a function, functools.partial is the perfect helper: it allows to define a new function fixing certain arguments.

functools is a powerful module offering lots of handy functionality. In a previous post we already saw the lru_cache decorator — here we will introduce partial, which allows to define “partial functions”: we can define new functions from an existing one, fixing some of the arguments.
The following code defines foo_partial, which is a new function derived from foo with the arguments a = “a1”, b = “b1”, c = 1:
from functools import partial
def foo(a, b, c, d):
print(f"Calling foo with: {a}, {b}, {c}, {d}")
foo_partial = partial(foo, "a1", "b1", 1)
foo_partial("d")foo_partial can then be called with the only remaining argument, d. Note that we can only fix the first N arguments of a function — thus you have to set the parameter order accordingly — and the last M parameters can be left open.
Let’s finish with another example introducing named functions for the first 3 powers:
from functools import partial
def exponentiate(base: int, exponent: float) -> float:
return base**exponent
square = partial(exponentiate, 2)
cube = partial(exponentiate, 3)
biquadrate = partial(exponentiate, 4)This post is part of a series show-casing important Python concepts quickly. You can find the other parts here:
- Part 1: Lambda Functions in Python
- Part 2: Iterators in Python
- Part 3: Generators and Generator Expressions in Python
- Part 4: Advanced Iteration in Python with enumerate() and zip()
- Part 5: Managing Resources in Python with Context Managers (with statement)
- Part 6: Generating Temporary Files and Directories in Python
- Part 7: Logging in Python
- Part 9: f-Strings in Python
