Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - value unpacking order in method parameters

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'
like image 931
Łukasz Avatar asked Nov 20 '19 19:11

Łukasz


People also ask

How do I unpack a parameter in Python?

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.

Does the order of parameters matter in Python?

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.

Does order matter for parameters?

An example would be ADD : ADD(1,2) and ADD(2,1) can be used interchangeably, the order of parameters does not matter.


1 Answers

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.

like image 165
blhsing Avatar answered Sep 23 '22 21:09

blhsing