Search code examples
pythonfunctiondictionarykeyword-argument

Dictionary Unpacking Operator **


why using this line of code in python gives error:

required, *args, **kwargs = "Welcome to...", 1, 2, 3, site='stackoverflow.com'
                 ^
                 SyntaxError: invalid syntax

while using it in function signatures is ok like:

def function1(required, *args, **kwargs):
    pass

function1("Welcome to...", 1, 2, 3, site='stackoverflow.com')

Solution

  • My guess is because if we want this **kwargs to work, we have to have keyword-argument on the right hand side(It should be converted to dictionary) just like you did :

    required, *args, **kwargs = "Welcome to...", 1, 2, 3, site='stackoverflow.com'
    

    But as we know right hand side of an assignment is evaluated fist(then the unpacking occurs). so in this case you can think of an another assignment in an expression which is invalid. for example :

    a = (1, 2, 3)       # Valid
    b = (1, 2, var=20)  # Invalid
    

    By looking at:

    from dis import dis
    dis('a, b, c = 5, 4, 3')
    
    
      1           0 LOAD_CONST               0 ((5, 4, 3))
                  2 UNPACK_SEQUENCE          3
                  4 STORE_NAME               0 (a)
                  6 STORE_NAME               1 (b)
                  8 STORE_NAME               2 (c)
                 10 LOAD_CONST               1 (None)
                 12 RETURN_VALUE
    

    Python tries to build a tuple from right hand side of the assignment, you can't have an assignment statement in there. I think same thing is happened and that's the reason.