How does functools.partial work and when is it useful?
Short answer
partial creates a new callable with some positional or keyword arguments pre-filled, returning a function with a smaller remaining signature.
Advertisement
AModel answer
partial creates a new callable with some positional or keyword arguments pre-filled, returning a function with a smaller remaining signature. It's useful for adapting a general function to a specific callback interface, like event handlers or map() calls, without writing a wrapper function or lambda.
from functools import partial
def power(base, exp):
return base ** exp
square = partial(power, exp=2)
print(square(5)) # 25Real-world example
A GUI framework binds partial(handle_click, button_id=3) as a callback so the click handler already knows which button fired.
Likely follow-ups
- How is partial different from a lambda?
- Can you partial a method?
Related topics