Sub topic 11
Fixing arguments with functools.partial
This chapter assumes you can define functions with def, use default values, *args and **kwargs, and that you have seen sorted, map and closures. Here you will use functools.partial to turn a many-argument function into a simpler one.
What partial does
functools.partial takes a function and some arguments. It returns a new callable that already has those arguments filled in. This is called partial application. When you call the new callable, it adds your arguments after the stored ones and calls the original function.
from functools import partial
from operator import mul
triple = partial(mul, 3)
print(triple(7)) # 21triple(7) runs mul(3, 7). The result is a function of one argument, which is the shape that map, sorted and callbacks expect.
Fixing keyword arguments
You can fix keyword arguments too. This is the usual way to fix an argument that is not first in the signature.
from functools import partial
binary = partial(int, base=2)
print(binary("1010")) # 10
print(binary.func, binary.args, binary.keywords)
# <class 'int'> () {'base': 2}The returned object exposes func, args and keywords, which helps when debugging. Call-time keywords override stored ones:
from functools import partial
def power(base, exp):
return base ** exp
square = partial(power, exp=2)
print(square(5)) # 25
print(square(5, exp=3)) # 125Positional arguments can only be fixed from the left. To fix exp without fixing base, use a keyword as above.
Using partial with higher-order functions
Because the result takes fewer arguments, it fits where a one-argument function is required:
from functools import partial
from operator import mul
scaled = list(map(partial(mul, 10), [1, 2, 3]))
print(scaled) # [10, 20, 30]partial or lambda?
partial(mul, 3) does the same job as lambda x: mul(3, x). They differ in when values are read. partial stores the argument values when you create it. A lambda looks up names when it runs, which is the late-binding behavior from earlier in this tutorial.
from functools import partial
from operator import mul
x = 10
with_partial = partial(mul, x)
with_lambda = lambda n: mul(x, n)
x = 99
print(with_partial(2)) # 20
print(with_lambda(2)) # 198The partial object kept the value 10. The lambda read x after it changed to 99.
| Need | Better choice |
|---|---|
| Fix some arguments of an existing function | `partial` |
| Freeze values at creation time | `partial` |
| Compute something new from the argument | `lambda` or `def` |
| Fix an argument that is not on the left | `partial` with a keyword |
Common errors
- Passing the fixed argument in the wrong position.
partial(pow, 2)fixes the base, sopartial(pow, 2)(3)is2 ** 3, not3 ** 2. - Expecting
partialto call the function. It only builds a new callable. You still have to call the result. - Fixing an argument by position and then also passing it by keyword at call time. Python raises
TypeErrorfor multiple values.
Exercise
Using functools.partial and the built-in pow, create a function cube so that cube(4) returns 64. Which argument must you fix, and how?
Show answer
pow(base, exp) takes the exponent second, so fix it by keyword: cube = partial(pow, exp=3). Then cube(4) runs pow(4, exp=3) and returns 64. Fixing it positionally with partial(pow, 3) would make the base 3 instead.