Sub topic 2
Looking inside a partial object
This chapter assumes you can call functools.partial to pre-fill arguments, and that you know the difference between positional and keyword arguments. You will learn what a partial object stores, how it combines stored and new arguments at call time, and how to inspect it when debugging.
What a partial object stores
A partial object is a small callable that holds three things. It exposes each of them as an attribute:
| Attribute | Meaning |
|---|---|
| `func` | The original callable that will be called |
| `args` | A tuple of the positional arguments fixed in advance |
| `keywords` | A dict of the keyword arguments fixed in advance |
The example below creates a partial with one positional and one keyword argument, then reads all three attributes.
from functools import partial
def connect(host, port, *, timeout=10):
return f"{host}:{port} timeout={timeout}"
conn = partial(connect, "localhost", timeout=5)
print(conn.func is connect) # True
print(conn.args) # ('localhost',)
print(conn.keywords) # {'timeout': 5}
print(conn(8080)) # localhost:8080 timeout=5These attributes are read-only. Assigning conn.func = something_else raises AttributeError. To change the pre-filled values, build a new partial.
How arguments are combined
When you call a partial, Python builds the final call in a fixed order:
- The stored
argscome first. - The arguments you pass at call time follow them.
- The stored
keywordsand the call-time keywords are merged. If a name appears in both, the call-time value wins.
The next example shows the override rule and the positional order.
from functools import partial
def connect(host, port, *, timeout=10):
return f"{host}:{port} timeout={timeout}"
conn = partial(connect, "localhost", timeout=5)
print(conn(8080, timeout=1)) # localhost:8080 timeout=1
def power(base, exponent):
return base ** exponent
two_to = partial(power, 2) # fixes base=2 by position
print(two_to(3)) # 8Stored positional arguments always sit on the left. You cannot pre-fill the second positional parameter and leave the first open. Use a keyword for that, as in partial(power, exponent=2).
Nested partials are flattened
If you wrap a partial in another partial, Python does not stack two layers. It merges them into one object that points at the original function.
from functools import partial
def connect(host, port, *, timeout=10):
return f"{host}:{port} timeout={timeout}"
inner = partial(connect, "localhost")
outer = partial(inner, timeout=3)
print(outer.func is connect) # True
print(outer.args) # ('localhost',)
print(outer.keywords) # {'timeout': 3}
print(outer(9000)) # localhost:9000 timeout=3Because of this, func always leads back to the real underlying function, however many times you refine a partial. That makes it safe to use for debugging.
Using the attributes in practice
The attributes are handy when you log or test code that receives callables from elsewhere. This helper describes any callable, including partials.
from functools import partial
def describe(fn):
if isinstance(fn, partial):
name = getattr(fn.func, "__name__", repr(fn.func))
return f"partial of {name}, args={fn.args}, keywords={fn.keywords}"
return getattr(fn, "__name__", repr(fn))
def greet(greeting, name):
return f"{greeting}, {name}"
hello = partial(greet, "Hello")
print(describe(hello)) # partial of greet, args=('Hello',), keywords={}
print(describe(greet)) # greetPrinting a partial directly also helps. Its repr shows the function and the stored arguments, for example functools.partial(<function greet at 0x...>, 'Hello'). The memory address differs on every run, so do not compare it in tests. Compare func, args, and keywords instead.
Common mistakes
- Mutating
keywords. The dict is technically mutable, but changing it alters a shared object that other code may hold. Create a new partial instead. - Expecting to skip a leading positional parameter. Positional pre-filling always starts at the first parameter.
- Forgetting that call-time keywords override stored ones. A pre-filled
timeout=5is a default, not a lock.
Exercise
Given def f(a, b, c): return (a, b, c), p = partial(f, 1, c=3), and q = partial(p, c=9), what do q.func is f, q.args, and q.keywords show, and what does q(2) return?
Show answer
q.func is f is True because nested partials are flattened. q.args is (1,). q.keywords is {'c': 9}, because the outer keyword replaces the inner one. q(2) returns (1, 2, 9): the stored 1 comes first, then the call-time 2, with c=9 supplied by keyword.