Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial function call as an argument python [duplicate]

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.

like image 636
Masa Avatar asked Dec 07 '22 16:12

Masa


1 Answers

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.

like image 103
Willem Van Onsem Avatar answered Dec 27 '22 11:12

Willem Van Onsem