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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With