python – TypeError: got multiple values for argument
python – TypeError: got multiple values for argument
This happens when a keyword argument is specified that overwrites a positional argument. For example, lets imagine a function that draws a colored box. The function selects the color to be used and delegates the drawing of the box to another function, relaying all extra arguments.
def color_box(color, *args, **kwargs):
painter.select_color(color)
painter.draw_box(*args, **kwargs)
Then the call
color_box(blellow, color=green, height=20, width=30)
will fail because two values are assigned to color
: blellow
as positional and green
as keyword. (painter.draw_box
is supposed to accept the height
and width
arguments).
This is easy to see in the example, but of course if one mixes up the arguments at call, it may not be easy to debug:
# misplaced height and width
color_box(20, 30, color=green)
Here, color
is assigned 20
, then args=[30]
and color
is again assigned green
.
I had the same problem that is really easy to make, but took me a while to see through.
I had copied the declaration to where I was using it and had left the self argument there, but it took me ages to realise that.
I had
self.myFunction(self, a, b, c=123)
but it should have been
self.myFunction(a, b, c=123)
python – TypeError: got multiple values for argument
This also happens if you forget self
declaration inside class methods.
Example:
class Example():
def is_overlapping(x1, x2, y1, y2):
# Thanks to https://stackoverflow.com/a/12888920/940592
return max(x1, y1) <= min(x2, y2)
Fails calling it like self.is_overlapping(x1=2, x2=4, y1=3, y2=5)
with:
{TypeError} is_overlapping() got multiple values for argument x1
WORKS:
class Example():
def is_overlapping(self, x1, x2, y1, y2):
# Thanks to https://stackoverflow.com/a/12888920/940592
return max(x1, y1) <= min(x2, y2)