Is there any way a following code works?
def f1(f2, x):
return f2(x)
def f2(y, z):
return y + z
f1(f2(10, ), 20)
output 30
f2
function misses z
. So, I want f1
to pass an argument, x
, to f2
as z
.
I will appreciate any help.
Yes, this is what functools.partial
is all about:
from functools import partial
f1(partial(f2, 10), 20)
partial
takes as input a function f
, an an arbitrary number of unnamed and named parameters. It constructs a new function where the unnamed and named parameters are filled in already.
It is somewhat equivalent to:
def partial(func, *partialargs, **partialkwargs):
def g(*args, **kwargs):
fargs = partialargs + args
fkwargs = partialkwargs.copy()
fkwargs.update(kwargs)
return func(*farg, **fkwargs)
return g
But functools
will reduce the overhead significantly compared with the above implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With