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

16 投票
4 回答
17451 浏览
提问于 2025-04-16 05:04

在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 个回答

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

撰写回答