Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python TypeError: multiple arguments with functools.partial [duplicate]

I ran into an error when using partial from the functools library.

from functools import partial
def add(x,a,b):
    return x + 10*a + 100*b

add = partial(add, x=2, b=3)
print (add(4))

I get the error:

TypeError: add() got multiple values for argument 'x'

I know that this can be fixed by bringing forward a to the first positional argument of add like:

def add(b,a,x):
    return x + 10*a + 100*b

add = partial(add, x=2, a=3)
print (add(4))

which correctly gives out: 432

My question is whether there is a way to keep the order of x,a,b intact within the add function and altering the partial function to give out the correct result. This is important because something like the add function is used elsewhere and so it is important for me to keep the order in the original add function intact.

I don't want to use a keyword argument with the function like print (add(a = 4)) because I want it as an input to a map function For example I want to do something like this: print (list(map(add,[1,2,3]))) print (min([1,2,3], key = add)))

like image 395
piccolo Avatar asked Jun 27 '26 04:06

piccolo


1 Answers

The only way to resolve you issue is to use keyword arguments with this function like so

print (add(b=4))

Because using it like this print (add(4)) assigns it to first parameter which partial already defined so x is passed twice

EDIT

You can also use partial with positional arguments

like so:

from functools import partial


def add(x, a, b):
    return x + 10 * a + 100 * b


add = partial(add, 2, 3)
print(add(4))

The second solution is possible because x and a are the first two parameters. The approach with keyword arguments is used when you do not want define consecutive parameters starting from the first.

like image 61
CodeSamurai777 Avatar answered Jun 28 '26 17:06

CodeSamurai777



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!