Sub topic 1
Pre-filling arguments with partial
Many functions are almost what you need. They take one argument more than the caller can supply, or they have an option you always set the same way. functools.partial wraps such a function in a new callable with some arguments already filled in. This chapter covers how partial builds that callable, how stored and call-time arguments combine, and the errors that come up most often.
Prerequisites
This chapter assumes you can do the following:
- Define and call Python functions, including calls that mix positional and keyword arguments.
- Treat functions as values: assign them to names, pass them to other functions, and return them.
- Read
*argsand**kwargsin a function signature.
You don't need decorators for this chapter. They come in later chapters, where partial and decorators meet.
The working model
partial(func, *args, **keywords) returns a new callable object. It does not call func. It stores func, the positional arguments, and the keyword arguments. When you later call the new object, it builds a combined call to func from three parts: the stored positional arguments first, then your new positional arguments, then the stored keywords updated by your new keywords.
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)) # 8Calling square(5) is the same as calling power(5, exponent=2). The result is a general function turned into a specialized one without writing a new def.
Pre-filling positional arguments
Positional arguments you give to partial fill parameters from the left.
from functools import partial
def power(base, exponent):
return base ** exponent
two_to = partial(power, 2)
print(two_to(10)) # 1024Here 2 is bound to base, and the call-time 10 becomes exponent. The result is power(2, 10).
You can only pre-fill a prefix of the positional parameters this way. You can't fix exponent positionally and leave base open, because the stored arguments always come first. To fix a later parameter, pass it by keyword, as square did above. This is the main reason keyword pre-filling is the more common form.
Pre-filling keyword arguments
Keyword pre-filling works well with functions that have optional parameters. The built-in int takes a base keyword.
from functools import partial
basetwo = partial(int, base=2)
basehex = partial(int, base=16)
print(basetwo("101")) # 5
print(basehex("ff")) # 255The same idea works with print, whose sep, end, and file keywords are often fixed for a whole program.
from functools import partial
info = partial(print, "[info]", sep=" | ")
info("started", "ok") # [info] | started | okThe stored positional "[info]" comes first, then the call-time "started" and "ok", and sep is applied to the combined list.
What happens when arguments collide
Call-time keywords override stored keywords. Call-time positional arguments cannot override stored positional ones, because they are appended after them.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(5, exponent=3)) # 125, the call-time keyword winsThe override is useful. A partial acts as a set of defaults that any caller can still change.
The positional case fails in a different way. Pre-filling base positionally and then passing base by keyword gives Python two values for the same parameter.
from functools import partial
def power(base, exponent):
return base ** exponent
two_to = partial(power, 2)
try:
two_to(base=3)
except TypeError as exc:
print(exc) # power() got multiple values for argument 'base'The same error appears whenever a stored positional argument and a call-time keyword target one parameter. When you see "multiple values for argument", check which parameters your stored positional arguments occupy.
Where partial earns its keep
partial is most useful where an API expects a callable with a fixed signature, and your function needs more arguments than that signature provides.
The first case is map, sorted, filter, and similar functions that call your function with a single argument.
from functools import partial
def power(base, exponent):
return base ** exponent
print(list(map(partial(power, exponent=2), [1, 2, 3]))) # [1, 4, 9]
print(list(map(partial(round, ndigits=1), [3.14159, 2.71828]))) # [3.1, 2.7]The second case is callbacks. GUI toolkits, event systems, and thread or process pools often call your function with a fixed set of arguments. partial carries the extra context along.
from functools import partial
from concurrent.futures import ThreadPoolExecutor
def fetch(url, timeout):
return f"{url} (timeout={timeout})"
urls = ["a.example", "b.example"]
with ThreadPoolExecutor() as pool:
results = list(pool.map(partial(fetch, timeout=5), urls))
print(results) # ['a.example (timeout=5)', 'b.example (timeout=5)']The third case is configuration. You can build a family of related functions from one general function and give each a clear name.
from functools import partial
def format_price(amount, currency, decimals):
return f"{amount:.{decimals}f} {currency}"
in_euros = partial(format_price, currency="EUR", decimals=2)
in_yen = partial(format_price, currency="JPY", decimals=0)
print(in_euros(9.5)) # 9.50 EUR
print(in_yen(1234.5)) # 1234 JPY1234.5 formats as 1234 because Python rounds half to even at zero decimals.
partial compared with lambda and def
You can often write the same thing with a lambda or a small def. The differences matter.
| Approach | Arguments are fixed | Caller can override | Picklable | Notes |
|---|---|---|---|---|
| `partial(f, exponent=2)` | When created | Keywords, yes | Yes, if `f` and the arguments are | Has no `__name__` of its own |
| `lambda x: f(x, 2)` | Looked up when called | Only what you write in | No | Free to reshape arguments |
| `def square(x): ...` | Looked up when called | Only what you write in | Yes, if defined at module level | Has a name and docstring |
The lasting difference is when values are read. A partial captures its arguments at creation time. A lambda reads names from the enclosing scope when it is called. This difference causes the best-known closure bug.
from functools import partial
def power(base, exponent):
return base ** exponent
with_lambda = [lambda x: power(x, e) for e in (1, 2, 3)]
with_partial = [partial(power, exponent=e) for e in (1, 2, 3)]
print([f(2) for f in with_lambda]) # [8, 8, 8]
print([f(2) for f in with_partial]) # [2, 4, 8]Every lambda reads the same variable e, which holds 3 after the loop ends. Each partial stored its own value when it was created. Picklability matters when you send a callable to another process, as multiprocessing does. A lambda can't be pickled, but a partial of a module-level function can.
Edge cases and common errors
Arguments are stored by reference
partial does not copy what you give it. A stored mutable object is shared by every call.
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']This is sometimes what you want. It is a bug if you expected a fresh list on each call. The same rule applies to mutable default arguments in a def.
Mistakes surface at call time
partial does not check the stored arguments against the function's signature when you create it. A misspelled keyword is accepted without complaint.
from functools import partial
def power(base, exponent):
return base ** exponent
broken = partial(power, expnent=2) # no error yet
try:
broken(5)
except TypeError as exc:
print(exc) # power() got an unexpected keyword argument 'expnent'The traceback points at the call, not at the line that built the partial. If a partial fails far from where you created it, look at its construction first.
Partials have no name or docstring
A partial object is not a function. It has no __name__, and its __doc__ describes the partial class, not your function.
from functools import partial
def power(base, exponent):
"""Raise base to exponent."""
return base ** exponent
square = partial(power, exponent=2)
print(hasattr(square, "__name__")) # FalseTools that print or log a callable's name will show something unhelpful, such as functools.partial(<function power at 0x...>, exponent=2). If the name matters, wrap the call in a def. The chapter on wraps returns to this problem from the decorator side.
Wrapping a partial flattens it
If you pass a partial to partial, CPython merges the two instead of nesting them. The behavior is the same either way.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
five_squared = partial(square, 5)
print(five_squared()) # 25The stored pieces are also visible through the func, args, and keywords attributes. The next chapter inspects those.
Summary of the rules
partial(func, *args, **kwargs)stores the call and runs nothing.- Stored positional arguments come first, followed by call-time positional arguments.
- Call-time keywords override stored keywords.
- Arguments are read once at creation and shared by reference.
- Signature errors appear when the partial is called.
- A partial has no
__name__of its own.
Exercise
Given def volume(length, width, height): return length * width * height, you write box = partial(volume, 2, height=4). What does box(3) return, and what does box(3, height=5) return?
Show answer
box(3) calls volume(2, 3, height=4) and returns 24. box(3, height=5) replaces the stored keyword and calls volume(2, 3, height=5), so it returns 30. The stored 2 fills length and the call-time 3 fills width.
Exercise
What error does partial(power, 2)(base=3) raise, given def power(base, exponent)? Why does it happen, and how would you fix the code if you wanted to fix exponent instead?
Show answer
It raises TypeError: power() got multiple values for argument 'base'. The stored positional 2 already fills base, and the call-time keyword base=3 targets the same parameter. To fix exponent, pass it by keyword: partial(power, exponent=2), then call it with the base value, as in square(3).
Exercise
A loop builds [partial(power, exponent=e) for e in (1, 2, 3)], and a second loop builds [lambda x: power(x, e) for e in (1, 2, 3)]. Calling each function in both lists with 2 gives different results. What are the results, and why do they differ?
Show answer
The partials give [2, 4, 8]. The lambdas give [8, 8, 8]. Each partial stores the value of e when it is created. Every lambda looks up e when it is called, and by then the loop has finished and e is 3.