为什么拆包元组会导致语法错误?

16

在 Python 中,我写了这个:

bvar=mht.get_value()
temp=self.treemodel.insert(iter,0,(mht,False,*bvar))
我试图将bvar扩展为函数调用的参数。 但是它返回了:
File "./unobsoluttreemodel.py", line 65
    temp=self.treemodel.insert(iter,0,(mht,False,*bvar))
                                                 ^
SyntaxError: invalid syntax

发生了什么?应该是正确的,对吧?

4个回答

39

更新:这个行为在Python 3.5.0中得到修复,参见PEP-0448

建议允许在元组、列表、集合和字典显示中进行解包操作:

*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}

24

如果你想将最后一个参数作为元组 (mnt, False, bvar[0], bvar[1], ...) 传递,你可以使用以下方法

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

在Python 3.x中,扩展调用语法*b只能在调用函数, 函数参数元组解包中使用。

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

元组字面量不符合这些情况之一,因此会导致语法错误。
>>> (1, *y)
  File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target

1
对的,* 解析操作符不能用于创建元组。 - AndiDog

2
不,这不正确。参数扩展只适用于函数参数中,而不适用于元组内部。
>>> 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

0

您似乎在其中有一个多余的括号层级。请尝试:

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

你多余的括号试图使用 * 语法创建一个元组,这是一个语法错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接