Search code examples
pythonpartialfunctools

Using functools partial with multiple arguments


Let's assume, I have a function

def func(u,v,w,x, alpha = 4, beta = 5):
    print('u ',u)
    print('v ',v)
    print('x ',w)
    print('u ',x)
    print('** kwarqs: alpha ',alpha)
    print('** kwarqs: beta ',beta)
    return u*4 + v*3 + w*2 + x

I now want to make it a partial-function by using functools.partial. I set the u,v,w variable to a constant and create a function $$part=f(x)|_{u,v,w = \text{const}}$$

u = 2
v = 4
w = 5

part = partial(func,u,v,w, alpha = 'Hello 1', beta = 'Hello 2')
print(part(4))

The result is

u  2
v  4
w  5
x  4   # This is the remaining free variable
** kwarqs: alpha  Hello 1
** kwarqs: beta  Hello 2
34

How can I create functions

f(u) #or f(v),f(w)
f(v,x) #or all other variable combinations
f(v,alpha) # a combination of args and kwargs

?

Best regards


Work arounds are also welcome.


Solution

  • Can I recommend the use of lambda for your case.

    f1 = lambda u : func(u,v,w,x, alpha = 4, beta = 5) 
    f2 = lambda v, x: func(u,v,w,x, alpha = 4, beta = 5) 
    f3 = lambda v, alpha: func(u,v,w,x, alpha = alpha, beta = 5)  
    

    The usage is the same as what you wanted:

    f1(u) #or f(v),f(w)
    f2(v,x) #or all other variable combinations
    f3(v,alpha) # a combination of args and kwargs