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 closures and functions that return functions from earlier chapters. It covers functools.partial: what it builds, how it differs from a lambda or a closure, and where it fails.
What partial application is
Partial application means taking a function that needs several arguments, supplying some of them now, and getting back a new function that needs only the rest. In Python you do this with functools.partial.
from functools import partial
from operator import mul
triple = partial(mul, 3)
print(triple(7)) # 21partial(mul, 3) does not call mul. It returns a callable object that remembers mul and the argument 3. When you call triple(7), that object calls mul(3, 7).
The signature is:
partial(func, /, *args, **keywords)The result is a functools.partial object. It is not a function created by def or lambda, but it is callable and you can pass it anywhere a function is expected.
Fixing positional arguments
Positional arguments given to partial are placed at the front of the final call. Arguments you supply later are appended after them.
from functools import partial
def power(base, exponent):
return base ** exponent
two_to = partial(power, 2)
print(two_to(10)) # 1024
print(two_to(3)) # 8Here two_to(10) becomes power(2, 10). The fixed argument is base, because positional arguments fill parameters from the left.
This means you can only fix leading positional parameters this way. To fix exponent and leave base open, use a keyword argument.
Fixing keyword arguments
Keyword arguments given to partial are stored and passed on every call.
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)) # 125Because exponent is fixed by name, the caller supplies only base. This is the usual way to fix a parameter that is not first.
A keyword fixed by partial is a default, not a lock. The caller can override it:
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(5, exponent=4)) # 625Later keywords replace earlier ones. Positional arguments cannot be overridden this way. If you fix base positionally and then pass base= as a keyword, Python raises a TypeError because the parameter would receive two values.
from functools import partial
def power(base, exponent):
return base ** exponent
two_to = partial(power, 2)
try:
two_to(base=3, exponent=2)
except TypeError as error:
print(error) # power() got multiple values for argument 'base'Comparing partial, lambda and a closure
All three can build a specialized function from a general one. The following are equivalent:
from functools import partial
def power(base, exponent):
return base ** exponent
by_partial = partial(power, exponent=2)
by_lambda = lambda base: power(base, 2)
def make_power(exponent):
def inner(base):
return power(base, exponent)
return inner
by_closure = make_power(2)
print(by_partial(6), by_lambda(6), by_closure(6)) # 36 36 36The differences are practical:
| Feature | `partial` | `lambda` | Closure with `def` |
|---|---|---|---|
| Length for a simple case | Shortest | Short | Longest |
| Values fixed when | Creation time | Call time (late binding) | Call time (late binding) |
| Inspectable | `.func`, `.args`, `.keywords` | No | Limited |
| Can add logic around the call | No | One expression | Yes |
| Shows a useful `repr` | Yes | No | No |
The second row matters most. A partial stores the actual values at the moment you create it. A lambda or closure looks up variables when it runs. That makes partial immune to the late-binding bug from the earlier chapter.
from functools import partial
def show(n):
return n
late = [lambda: show(i) for i in range(3)]
early = [partial(show, i) for i in range(3)]
print([f() for f in late]) # [2, 2, 2]
print([f() for f in early]) # [0, 1, 2]Each partial(show, i) copies the current value of i into the object, so later loop iterations cannot change it.
There is a flip side. If you fix a mutable object, the partial holds a reference to that same object. It does not copy it.
from functools import partial
def add_item(item, bucket):
bucket.append(item)
return bucket
shared = []
add_to_shared = partial(add_item, bucket=shared)
add_to_shared("a")
add_to_shared("b")
print(shared) # ['a', 'b']Both calls changed the same list. Early binding fixes the reference, not the contents.
Inspecting a partial object
A partial exposes three attributes:
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square.func is power) # True
print(square.args) # ()
print(square.keywords) # {'exponent': 2}
print(square) # functools.partial(<function power at 0x...>, exponent=2)This makes a partial easy to debug. A lambda prints as <function <lambda> at 0x...>, which tells you nothing about what it does.
You can also nest partials. Python flattens them, so partial(partial(f, 1), 2) behaves like partial(f, 1, 2).
Two limits to know. A partial object has no __name__ or __doc__ of the wrapped function by default, so tools that read func.__name__ can fail. And it is not a real function, so it does not become a bound method when stored as a class attribute. Use functools.partialmethod for that case.
Where partial is useful
Adapting a function to a callback API
Many APIs call your function with a fixed set of arguments. partial lets you supply the extra ones.
from functools import partial
def greet(greeting, name):
return f"{greeting}, {name}!"
names = ["Ada", "Grace", "Linus"]
hello = partial(greet, "Hello")
print(list(map(hello, names)))
# ['Hello, Ada!', 'Hello, Grace!', 'Hello, Linus!']map calls hello(name) for each name. The greeting was fixed in advance.
Configuring built-in functions
from functools import partial
int_from_binary = partial(int, base=2)
print(int_from_binary("1010")) # 10
print(int_from_binary("1111")) # 15int accepts a base keyword, so fixing it gives a clear, named converter.
Building key functions
Key functions for sorted, min and max take one argument. If your comparison needs a second piece of information, partial supplies it.
from functools import partial
def distance(origin, point):
return abs(point - origin)
readings = [3, 9, 14, 6, 1]
nearest_to_8 = partial(distance, 8)
print(sorted(readings, key=nearest_to_8))
# [9, 6, 3, 14, 1]
print(min(readings, key=nearest_to_8)) # 9Here nearest_to_8(point) becomes distance(8, point). The values are ordered by their distance from 8.
Passing arguments to threads and tasks
APIs such as threading.Thread(target=...) and loop.run_in_executor take a callable and sometimes cannot forward arguments. partial packages the arguments with the callable.
Failure modes and gotchas
- Argument order. Positional fixing starts at the left. If the parameter you want to fix is not first, use a keyword.
- Positional-only parameters. Some built-ins accept certain parameters only by position, so you cannot fix them by keyword. Check the signature before you rely on a keyword.
- Overriding. A fixed keyword can be overridden by the caller. A fixed positional argument cannot be changed, and trying to pass it again by name raises
TypeError. - Mutable arguments. The
partialshares the object you gave it. Mutations are visible to every call. - Missing metadata. Decorators such as
functools.wrapsexpect__name__. Apartiallacks it, so wrapping one can raiseAttributeError. - Readability. A
partialwith many fixed arguments can be harder to read than a shortdefwith a name and docstring.
Choosing partial
Use partial when you only need to fix arguments of one existing function and nothing else. Use a lambda when you need a small expression around the call, such as lambda x: f(x) + 1. Use a def when the logic needs several statements, a name, or a docstring.
Exercises
Exercise
What does this code print, and why? from functools import partial def divide(a, b): return a / b half = partial(divide, b=2) print(half(10)) print(half(10, b=5))
Show answer
It prints 5.0 and then 2.0. The first call is divide(10, b=2). The second call overrides the fixed keyword, so it becomes divide(10, b=5). Fixed keyword arguments act as defaults that the caller can replace.
Exercise
Why does [partial(show, i) for i in range(3)] avoid the late-binding bug that [lambda: show(i) for i in range(3)] has?
Show answer
partial stores the current value of i inside the object at creation time. The lambda stores only a reference to the variable i and looks it up when called, after the loop has finished and i is 2.
Exercise
Write a call using partial that turns round into a function that always rounds to two decimal places, then use it on 3.14159.
Show answer
from functools import partial round2 = partial(round, ndigits=2) print(round2(3.14159)) # 3.14