Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does unpacking a tuple cause a syntax error?

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?

like image 986
asdacap Avatar asked Oct 06 '10 08:10

asdacap


People also ask

Is unpacking possible in a tuple?

In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments. “*_” is used to specify the arbitrary number of arguments in the tuple.

How does tuple unpacking work in Python?

When we are unpacking values into variables using tuple unpacking, the number of variables on the left side tuple must exactly match the number of values on the right side tuple . Otherwise, we'll get a ValueError .

What does unpacking a tuple mean?

Unpacking a tuple means splitting the tuple's elements into individual variables. For example: x, y = (1, 2) Code language: Python (python)

When unpacking a tuple What happens if the number of variables on the left doesn't match the number of items in the tuple?

Because parentheses of tuples can be omitted, multiple values can be assigned to multiple variables in one line as follows. An error is raised if the number of variables does not match the number of elements.


2 Answers

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}
like image 99
Ilya V. Schurov Avatar answered Oct 06 '22 12:10

Ilya V. Schurov


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
like image 43
kennytm Avatar answered Oct 06 '22 11:10

kennytm