Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python functools partial confusion

consider the following:

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

add_part = partial(add, c = 2, b = 1)
add_part(3)
312

Works fine. However:

def foo(x, y, z):
   return x+y+z

bar = partial(foo, y=3)

bar(1, 2)

barfs:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got multiple values for argument 'y'

Obviously I am missing something obvious, but what?

like image 435
Igor Rivin Avatar asked Oct 25 '25 04:10

Igor Rivin


1 Answers

The definition of partial() from the official functools documentation is:

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

That means that in your case partial() returns the foo() function with the signature modified as follow:

>>> from inspect import signature
>>> signature(bar)
<Signature (x, *, y=3, z)>

To solve your error, you could provide keyword arguments to the bar() function:

def foo(x, y, z):
   return x+y+z

bar = partial(foo, y=3)

bar(x=1, z=2)
like image 173
Kevin Hillairet Avatar answered Oct 26 '25 16:10

Kevin Hillairet