What is the display order of the various assignment forms in a python function call?

When I run the following code, I get an error, why? Wrong argument order?

def f(a, b, c, d):
    print a, b, c, d

f(1, b=2, *(3,), **{'d': 4})

This is the error I get:

Traceback (most recent call last):
  File "/home/asad/scripts/l.py", line 9, in <module>
    f(1, b=2, *(3,), **{'d': 4})
TypeError: f() got multiple values for keyword argument 'b'
[Finished in 0.1s with exit code 1]
+4
source share
3 answers

b=2 in a function call is not a variable assignment, but a keyword argument is passed.

You pass bin the keyword argument, but you also pass in the value 3(as the second positional argument), which is also b.

So, it breceives several values ​​in this call.

+5
source

It will work - pay attention to the order of presentation of things

 f(1, *(2,), c=3, **{'d': 4})
+1
source

b positional keyword.

:

: , . / , *.

: , (, name=) , **.

. , :

>>> f(1, b=2, *(3,), **{'d': 4})   # Same as f(1, b=2, 3, d=4)

1 3 a b. (b=2), b, , .

Some limitations

If you need more information on how calls are defined, see the docs . It is noteworthy that only keyword arguments can follow *expression, and **expressionshould be the last argument in the call.

Decision

Change the order of the arguments so that positional arguments are always specified:

>>> f(1, *(2,), c=3, **{'d': 4})   # Same as f(1, 2, c=3, d=4)
+1
source

All Articles