Python 中奇怪的语法解析错误?
我在这里错过了什么吗?为什么“损坏”部分下的代码不能工作?我正在使用Python 2.6。
#!/usr/bin/env python
def func(a,b,c):
print a,b,c
#Working: Example #1:
p={'c':3}
func(1,
b=2,
c=3,
)
#Working: Example #2:
func(1,
b=2,
**p)
#Broken: Example #3:
func(1,
b=2,
**p,
)
Am I missing something here? Why shouldn't the code under the "Broken" section work? I'm using Python 2.6.
#!/usr/bin/env python
def func(a,b,c):
print a,b,c
#Working: Example #1:
p={'c':3}
func(1,
b=2,
c=3,
)
#Working: Example #2:
func(1,
b=2,
**p)
#Broken: Example #3:
func(1,
b=2,
**p,
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 语法 中的相关部分:
这里的第一行允许在不使用 varargs/kwargs 时的最后一个参数(这就是第一个示例有效的原因)。但是,如果指定了 kwargs 参数,则不允许在其后放置逗号,如第二行和第三行所示。
顺便说一句,语法显示了一个有趣的事情:
这些都是合法的:
但这不是:
在
**kwargs
之后不允许使用逗号是有意义的,因为它必须始终是最后一个参数。我不知道为什么语言设计者选择不允许我的最后一个例子 - 也许是一个疏忽?This is the relevant bit from the grammar:
The first line here allows putting a comma after the last parameter when not using varargs/kwargs (this is why your first example works). However, you are not allowed to place a comma after the kwargs parameter if it is specified, as shown in the second and third lines.
By the way, here is an interesting thing shown by the grammar:
These are both legal:
but this is not:
It makes sense not to allow a comma after
**kwargs
, since it must always be the last parameter. I don't know why the language designers chose not to allow my last example though - maybe an oversight?Python 通常允许在逗号列表末尾使用额外的逗号(在参数列表和容器文字中)。这样做的主要目标是使代码生成稍微容易一些(您不必对最后一项进行特殊处理或对单例元组进行双重特殊处理)。
在语法的定义中,
**kwargs
被单独拉出,并且没有额外的可选逗号。据我想象,它对代码生成之类的实际问题没有帮助(** kwargs 永远是最后一件事,所以你不必对任何事情进行特殊处理),所以我不知道为什么 Python 会支持它。Python usually allows extra commas at the end of comma-lists (in argument lists and container literals). The main goal for this is to make code generation slightly easier (you don't have to special-case the last item or double-special-case a singleton tuple).
In the definition of the grammar,
**kwargs
is pulled out separately and without an extra optional comma. It wouldn't ever help with anything practical like code generation (**kwargs will always be the last thing so you do not have to special-case anything) as far as I can imagine, so I don't know why Python would support it.