6

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)))

Cœur
  • 37,241
  • 25
  • 195
  • 267
piccolo
  • 2,093
  • 3
  • 24
  • 56
  • 2
    Unfortunate that this was closed, but one solution is to do: `_add = partial(lambda a, x, b: add(x, a, b), x=2, b=3) print(list(map(_add, [1,2,3])))` observe the use of `_add` vs. `add` when reassigning. – salparadise Jul 29 '18 at 20:14
  • @salparadise ah very clever use of the lambda function – piccolo Jul 29 '18 at 20:49
  • @Imran Please mark the answer as correct – CodeSamurai777 Jul 30 '18 at 06:54
  • apologies @mrangry777 I had edited my question to something a bit different after you gave your answer but I changed the question far too late. I've ticked your answer now. – piccolo Jul 30 '18 at 10:56

1 Answers1

4

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.

CodeSamurai777
  • 3,285
  • 2
  • 24
  • 42