Why does unpacking a tuple cause a syntax error?

16,786

Solution 1

If you want to pass the last argument as a tuple of (mnt, False, bvar[0], bvar[1], ...) you could use

temp = self.treemodel.insert(iter, 0, (mht,False)+tuple(bvar) )

The extended call syntax *b can only be used in calling functions, function arguments, and tuple unpacking on Python 3.x.

>>> def f(a, b, *c): print(a, b, c)
... 
>>> x, *y = range(6)
>>> f(*y)
1 2 (3, 4, 5)

Tuple literal isn't in one of these cases, so it causes a syntax error.

>>> (1, *y)
  File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target

Solution 2

Update: this behavior was fixed in Python 3.5.0, see PEP-0448:

Unpacking is proposed to be allowed inside tuple, list, set, and dictionary displays:

*range(4), 4
# (0, 1, 2, 3, 4)

[*range(4), 4]
# [0, 1, 2, 3, 4]

{*range(4), 4}
# {0, 1, 2, 3, 4}

{'x': 1, **{'y': 2}}
# {'x': 1, 'y': 2}

Solution 3

Not it isn't right. Parameters expansion works only in function arguments, not inside tuples.

>>> def foo(a, b, c):
...     print a, b, c
... 
>>> data = (1, 2, 3)
>>> foo(*data)
1 2 3

>>> foo((*data,))
  File "<stdin>", line 1
    foo((*data,))
         ^
SyntaxError: invalid syntax
Share:
16,786
asdacap
Author by

asdacap

Updated on July 10, 2022

Comments

  • asdacap
    asdacap almost 2 years

    In Python, I wrote this:

    bvar=mht.get_value()
    temp=self.treemodel.insert(iter,0,(mht,False,*bvar))
    

    I'm trying to expand bvar to the function call as arguments. But then it returns:

    File "./unobsoluttreemodel.py", line 65
        temp=self.treemodel.insert(iter,0,(mht,False,*bvar))
                                                     ^
    SyntaxError: invalid syntax
    

    What just happen? It should be correct right?

  • AndiDog
    AndiDog over 13 years
    Right, the * resolution operator is not allowed for creating tuples.