partial function creates partial function application from another function. It is used to bind values to some of the function's arguments (or keyword arguments) and produce a callable without the already defined arguments.
>>> from functools import partial >>> unhex = partial(int, base=16) >>> unhex.__doc__ = 'Convert base16 string to int' >>> unhex('ca11ab1e') 3390155550
partial(), as the name suggests, allows a partial evaluation of a function.
Let's look at at following example:
In : from functools import partial In : def f(a, b, c, x): ...: return 1000*a + 100*b + 10*c + x ...: In : g = partial(f, 1, 1, 1) In : print g(2) 1112
g is created,
f, which takes four arguments(
a, b, c, x), is also partially evaluated for the first three arguments,
a, b, c,. Evaluation of
f is completed when
g is called,
g(2), which passes the fourth argument to
One way to think of
partial is a shift register; pushing in one argument at the time into some function.
partial comes handy for cases where data is coming in as stream and we cannot pass more than one argument.