How do you use functools.partial to create a new function with some arguments pre-filled?
Short answer
functools.partial(func, *args, **kwargs) returns a NEW callable that, when invoked, calls the ORIGINAL function with the pre-filled arguments PLUS whatever additional arguments are passed at call time — a clean, explicit alternative to writing a small wrapper lambda for the same…
Advertisement
AModel answer
functools.partial(func, *args, **kwargs) returns a NEW callable that, when invoked, calls the ORIGINAL function with the pre-filled arguments PLUS whatever additional arguments are passed at call time — a clean, explicit alternative to writing a small wrapper lambda for the same purpose.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2) # 'exponent' pre-filled
print(square(5)) # 25, equivalent to power(5, exponent=2)Real-world example
Creating a specialized, pre-configured version of a generic function, like a square() function derived from a general power() function.
Likely follow-ups
- How does functools.partial differ from simply writing an equivalent lambda that calls the original function?
Related topics