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

时间:2010-10-06 08:42:59

标签: python arguments tuples

在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 个答案:

答案 0 :(得分:37)

更新:此行为已在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}

答案 1 :(得分:24)

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

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

扩展调用语法*b只能在Python 3.x上的calling functionsfunction argumentstuple unpacking中使用。

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

答案 2 :(得分: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

答案 3 :(得分:0)

你似乎有更多级别的括号。尝试:

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

您的额外括号正在尝试使用*语法创建元组,这是一种语法错误。

相关问题