开箱参数:唯一命名的参数可能遵循*前pression [英] Unpacking arguments: only named arguments may follow *expression
问题描述
下面的精美作品在Python:
The following works beautifully in Python:
def f(x,y,z): return [x,y,z]
a=[1,2]
f(3,*a)
的元素 A
得到解压,如果你曾要求它像 F(3,1,2)
并返回 [3,1,2]
。太棒了!
The elements of a
get unpacked as if you had called it like f(3,1,2)
and it returns [3,1,2]
. Wonderful!
但我不能 A
元素解压到的第一个的两个参数:
But I can't unpack the elements of a
into the first two arguments:
f(*a,3)
而不是调用,像的F(1,2,3)
,我得到语法错误:只有命名的参数可能遵循*前pression。
Instead of calling that like f(1,2,3)
, I get "SyntaxError: only named arguments may follow *expression".
我只是想知道为什么它是这个样子,如果有任何巧招我可能不知道的拆包数组到参数列表的任意部分,而不诉诸临时变量。
I'm just wondering why it has to be that way and if there's any clever trick I might not be aware of for unpacking arrays into arbitrary parts of argument lists without resorting to temporary variables.
推荐答案
由于雷蒙德的Hettinger的回答指出,这可能会在Python 3的变化和的这里是一个有关的提案,这已被接受。
特别是有关当前问题,这里的这项提议可能发生的变化进行了讨论一句:
As Raymond Hettinger's answer points out, this may change in Python 3 and here is a related proposal, which has been accepted. Especially related to the current question, here's one of the possible changes to that proposal that was discussed:
只允许一个星号的前pression作为exprlist的最后一个项目。这将简化
拆包code位并允许出演前pression要分配的迭代器。这个
行为被拒绝,因为这将是太出人意料。
Only allow a starred expression as the last item in the exprlist. This would simplify the unpacking code a bit and allow for the starred expression to be assigned an iterator. This behavior was rejected because it would be too surprising.
因此,有与解压缩函数参数的限制实现的原因,但它确实是一个令人感到有点惊讶!
So there are implementation reasons for the restriction with unpacking function arguments but it is indeed a little surprising!
在此期间,这里是我一直在寻找解决方法,一种明显的在回顾:
In the meantime, here's the workaround I was looking for, kind of obvious in retrospect:
f(*(a+[3]))
这篇关于开箱参数:唯一命名的参数可能遵循*前pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!