Sub topic 1
Pre-filling arguments with partial
Prerequisites
This chapter assumes you can do the following:
- Define and call Python functions, including calls with keyword arguments.
- Treat functions as values that you can pass around and return.
- Tell hashable types from unhashable ones. This matters in later chapters, not in this one.
What partial does
functools.partial takes an existing callable and some arguments. It returns a new callable with those arguments already filled in. When you call the new callable, Python adds your new arguments to the stored ones and calls the original.
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(2)) # 8square is not a function you wrote with def. It is a partial object, and calling it runs power(5, exponent=2). Use it when you have a general function and need a specialized version of it.
flowchart LRThe block above is a placeholder syntax check only. The real diagram follows.
Fixing positional and keyword arguments
You can pre-fill positional arguments, keyword arguments, or both.
- Positional arguments fill parameters from the left, in order.
- Keyword arguments fill the parameter with that name.
from functools import partial
def power(base, exponent):
return base ** exponent
two_to = partial(power, 2) # base is fixed to 2
print(two_to(10)) # 1024
basetwo = partial(int, base=2)
print(basetwo("101")) # 5partial(power, 2) fixes base, because positional arguments start at the first parameter. To fix exponent and leave base free, you must use the keyword form, as square did earlier. A partial cannot skip a leading positional parameter any other way.
Overriding at call time
Keyword arguments stored in a partial are defaults, not locks. A keyword you pass at call time replaces the stored one.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(5)) # 25
print(square(5, exponent=4)) # 625This is useful, but it is also the source of the most common error. Passing the same parameter both ways raises a TypeError.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
try:
square(5, 3) # 3 lands in the exponent slot, which is already filled
except TypeError as error:
print(error) # power() got multiple values for argument 'exponent'The stored keyword fills exponent. Your extra positional 3 then also tries to fill it. If you see "multiple values for argument", check whether a partial has already supplied that parameter.
Where partial is useful
Partial objects fit places that expect a callable with a fixed signature, such as map, sorted(key=...), thread targets, and callbacks. In these places you cannot pass extra arguments yourself.
from functools import partial
def scale(factor, value):
return factor * value
double = partial(scale, 2)
print(list(map(double, [1, 2, 3]))) # [2, 4, 6]
print_csv = partial(print, sep=",")
print_csv("a", "b", "c") # a,b,cA lambda such as lambda v: scale(2, v) does the same job. Partial has two advantages. It states your intent ("this function with some arguments fixed") without a new function body. It also avoids the late-binding trap in loops, where every lambda sees the loop variable's final value.
from functools import partial
def scale(factor, value):
return factor * value
with_lambda = [lambda v: scale(n, v) for n in (1, 2, 3)]
with_partial = [partial(scale, n) for n in (1, 2, 3)]
print([f(10) for f in with_lambda]) # [30, 30, 30]
print([f(10) for f in with_partial]) # [10, 20, 30]The partial stores the value of n when it is created. The lambda looks n up when it runs, after the loop has finished.
Summary of the working model
| Call | Stored | Result |
|---|---|---|
| `partial(power, 2)(10)` | `base=2` | `power(2, 10)` |
| `partial(power, exponent=2)(5)` | `exponent=2` | `power(5, exponent=2)` |
| `partial(power, exponent=2)(5, exponent=4)` | `exponent=2`, overridden | `power(5, exponent=4)` |
| `partial(power, exponent=2)(5, 3)` | `exponent=2` | `TypeError` |
Exercise
Given def greet(greeting, name): return f"{greeting}, {name}!", create a callable hello so that hello("Ada") returns "Hello, Ada!". Then explain why partial(greet, name="Ada")("Hi") works, but partial(greet, name="Ada")("Hi", "Bob") fails.
Show answer
Use hello = partial(greet, "Hello"). The positional "Hello" fills greeting, and hello("Ada") supplies name. In partial(greet, name="Ada")("Hi"), the stored name is a keyword and "Hi" fills greeting, so the call is greet("Hi", name="Ada"). In the failing call, "Bob" is a second positional argument that fills name, which the partial has already set by keyword. Python raises a TypeError about multiple values for argument 'name'.