Sub topic 2
Looking inside a partial object
A partial object is a small callable that remembers a function and some arguments. This chapter shows how to read what it remembers, how a call is assembled from those pieces, and where a partial object differs from an ordinary function.
Prerequisites
This chapter assumes you can:
- define and call functions with positional and keyword arguments
- create a partial object with
functools.partial, as in the previous chapter - tell a callable object from a plain function
A partial is an object, not a function
partial(power, exponent=2) does not build a new function with def. It builds an instance of the class functools.partial. That instance is callable because the class defines a call method.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(type(square)) # <class 'functools.partial'>
print(callable(square)) # True
print(isinstance(square, partial)) # True
print(hasattr(square, "__name__")) # FalseThe last line is the first surprise. A function created with def or lambda has a __name__. A partial object does not, because it is not a function. Code that expects f.__name__ to exist, such as some logging helpers and decorators, can fail with AttributeError when it receives a partial object.
The three attributes
Every partial object stores exactly three things, and each has a public attribute.
| Attribute | Holds | For `partial(power, 2, exponent=3)` |
|---|---|---|
| `func` | The callable that will eventually run | `power` |
| `args` | A tuple of pre-filled positional arguments | `(2,)` |
| `keywords` | A dict of pre-filled keyword arguments | `{'exponent': 3}` |
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}
two_to = partial(power, 2)
print(two_to.args) # (2,)
print(two_to.keywords) # {}
print(two_to(10)) # 1024Look at two_to. A pre-filled positional argument always fills the leftmost parameters, so 2 became base. You cannot use positional pre-filling to fix only exponent. To do that, pass exponent by keyword, as square does.
You cannot reassign these attributes. square.func = print raises AttributeError: readonly attribute. The attributes are meant for inspection.
How a call is assembled
When you call a partial object, Python builds the real call from the stored parts and the new arguments. The rules are:
- Stored positional arguments come first, followed by the positional arguments from the call.
- Stored keyword arguments are merged with the keyword arguments from the call. If a name appears in both, the call-time value wins.
- The result is passed to
func.
In effect, p(*a, **k) runs p.func(*p.args, *a, **{**p.keywords, **k}).
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(5)) # 25
print(square(5, exponent=3)) # 125 (call-time keyword overrides the stored one)
print(square.keywords) # {'exponent': 2} (the stored value is unchanged)The override affects only that one call. The stored keywords stay as they were.
The merge rules cannot override a positional argument. If you pre-fill base by position and then pass base by keyword, the call fails:
from functools import partial
def power(base, exponent):
return base ** exponent
two_to = partial(power, 2)
try:
two_to(base=3)
except TypeError as error:
print(error) # power() got multiple values for argument 'base'The error names power, not the partial object. The partial object does not appear in the traceback as a separate frame. This can be confusing when you are debugging, so check args and keywords when you see an argument error.
Nested partials are flattened
You can wrap a partial object in another partial. The result does not stack two layers. In CPython, the constructor merges them into one object whose func is the original function.
from functools import partial
def power(base, exponent):
return base ** exponent
two_to = partial(power, 2)
two_cubed = partial(two_to, 3)
print(two_cubed.func is power) # True, not two_to
print(two_cubed.args) # (2, 3)
print(two_cubed()) # 8
a = partial(power, exponent=2)
b = partial(a, exponent=3)
print(b.keywords) # {'exponent': 3}
print(b(5)) # 125The merge follows the same rules as a call. The inner positional arguments come first. For keywords, the outer value replaces the inner one.
Flattening keeps call chains short and keeps func meaningful. After building a partial object in layers, you can still read func and get the underlying function.
Flattening is an implementation detail of CPython. The functools documentation does not require it. If you write code that walks through partial objects, handle both cases.
from functools import partial
def unwrap(p):
"""Return the innermost function and the combined stored arguments."""
args = ()
keywords = {}
while isinstance(p, partial):
args = p.args + args
keywords = {**p.keywords, **keywords}
p = p.func
return p, args, keywords
def power(base, exponent):
return base ** exponent
nested = partial(partial(power, 2), exponent=5)
func, args, keywords = unwrap(nested)
print(func.__name__, args, keywords) # power (2,) {'exponent': 5}The loop works whether or not the partial objects were flattened. If they were not flattened, each pass peels one layer.
Reading the signature
A partial object does not carry a def line, but inspect.signature can compute what remains to be supplied.
import inspect
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
two_to = partial(power, 2)
print(inspect.signature(power)) # (base, exponent)
print(inspect.signature(square)) # (base, *, exponent=2)
print(inspect.signature(two_to)) # (exponent)Two details are worth noting:
- A pre-filled positional argument disappears from the signature, as
basedid fortwo_to. - A pre-filled keyword argument stays, but it becomes keyword-only with a default. That is why
exponentappears after*forsquare. Once you pre-fill a keyword, any parameter after it must also be passed by keyword.
inspect.signature raises ValueError for some built-in callables that expose no signature, and that also applies to partial objects built on them. When a signature is unavailable, fall back on func, args, and keywords.
Building a readable description
The default repr of a partial object includes the function's address, such as functools.partial(<function power at 0x...>, exponent=2). The address changes on every run, so it is a poor choice for logs and tests. A small helper that reads the three attributes gives stable output.
from functools import partial
def power(base, exponent):
return base ** exponent
def describe(p):
name = getattr(p.func, "__name__", repr(p.func))
parts = [repr(a) for a in p.args]
parts += [f"{key}={value!r}" for key, value in p.keywords.items()]
return f"{name}({', '.join(parts)}, ...)"
print(describe(partial(power, exponent=2))) # power(exponent=2, ...)
print(describe(partial(power, 2, exponent=3))) # power(2, exponent=3, ...)The getattr fallback matters because func can itself be an object without a __name__, such as another callable class instance.
Giving a partial object a name
Partial objects have a __dict__, so you can attach attributes to them. This is a quick way to give one a __name__.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
square.__name__ = "square"
square.__doc__ = "Return base squared."
print(square.__name__) # square
print(square(7)) # 49Use this sparingly. The attribute lives on that one object. In CPython, a partial object that has extra attributes is also not flattened when you wrap it in another partial, so func will be the partial object instead of the original function. The unwrap helper above handles that case. If you need to copy a name, docstring, and other metadata from a function, functools.update_wrapper does it in one call. A later chapter covers it.
Pickling
A partial object can be pickled if its func, args, and keywords can all be pickled. A function defined at module level can. A lambda or a function defined inside another function cannot.
import pickle
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
restored = pickle.loads(pickle.dumps(square))
print(restored(6)) # 36This is one practical reason to prefer partial over a lambda when you pass a callable to something like multiprocessing, which pickles it to send it to another process. partial(power, exponent=2) pickles. lambda base: power(base, 2) does not.
Common mistakes
- Treating a partial object as a function. It has no
__name__and is not an instance oftypes.FunctionType.inspect.isfunction(square)returnsFalse. - Mutating
keywords. In CPython thekeywordsattribute is the dict the partial object uses, so changing it changes later calls. Treat it as read-only and create a new partial object instead. - Expecting positional pre-filling to skip parameters. Positional arguments always fill from the left. Use keywords to fix later parameters.
- Relying on flattening. It is a CPython behavior. Write inspection code that works with both nested and flat objects.
- Pre-filling a mutable value. The stored value is shared across every call. If you pass
partial(f, items=[]), every call sees the same list.
Exercises
Exercise
Given def area(width, height): return width * height and p = partial(area, 3), what are p.func is area, p.args, p.keywords, and p(4)? What does inspect.signature(p) show?
Show answer
p.func is area is True, p.args is (3,), p.keywords is {}, and p(4) is 12. The signature is (height), because the positional argument 3 filled width and removed it from the signature.
Exercise
What does this code print, and why? from functools import partial def power(base, exponent): return base ** exponent a = partial(power, 2) b = partial(a, exponent=4) print(b.func is power, b.args, b.keywords) print(b())
Show answer
It prints True (2,) {'exponent': 4} and then 16. In CPython the constructor flattens the nested partial, so func is power, the inner positional argument 2 is kept in args, and the outer keyword is stored in keywords. The call is power(2, exponent=4), which is 16.
Exercise
A logging helper calls func.__name__ on every callable it receives. It raises AttributeError when you pass partial(power, exponent=2). Give two ways to fix it.
Show answer
Either read the name defensively, for example getattr(func.func, "__name__", repr(func)) when func is a partial object, or give the partial object a name by assigning square.__name__ = "square" (or by using functools.update_wrapper) before passing it in.