def fun(a, b, c, d):
print('a:', a, 'b:', b, 'c:', c, 'd:', d)
why this one works
fun(3, 7, d=10, *(23,))
and prints out:
a: 3 b: 7 c: 23 d: 10
while this
fun(3, 7, c=10, *(23,))
does not
Traceback (most recent call last):
File "/home/lookash/PycharmProjects/PythonLearning/learning.py", line 10, in <module>
fun(3, 7, c=10, *(23,))
TypeError: fun() got multiple values for argument 'c'
When the arguments are in the form of a dictionary, we can unpack them during the function call using the ** operator. A double asterisk ** is used for unpacking a dictionary and passing it as keyword arguments during the function call.
It doesn't matter what order they are given in the parameter so long as the arguments in the call expression match the correct variable. Either way won't matter to the output string.
An example would be ADD : ADD(1,2) and ADD(2,1) can be used interchangeably, the order of parameters does not matter.
With *(23,)
, you are unpacking the values in the tuple (23,)
as positional arguments, following the positional arguments that are already defined, namely 3
for a
and 7
for b
, so 23
would be assigned to parameter c
, which is why fun(3, 7, d=10, *(23,))
works, but in fun(3, 7, c=10, *(23,))
you are also assigning to value 10
to c
as a keyword argument, so it is considered a conflict as c
cannot be assigned with both 23
and 10
.
Note that while legal, it is discouraged by some to unpack iterable arguments after keyword arguments, as discussed here, although the syntax is ultimately ruled to stay.
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