[英]How does definition foo(*, a=1) in python match the formal 'argument list' in documentation reference?
I've been studying *args
and **kwargs
in python recently and I've come across that in python 3 one can use bare *
as in the example from the title to indicate that no positional arguments are allowed after it. 我最近在python中研究过
*args
和**kwargs
,我在python 3中遇到过,可以使用裸*
如标题中的示例所示,表示之后不允许任何位置参数。
The problem is that I don't see how it matches the formal definition or 'argument list' in reference . 问题是我没有看到它与参考文献中的正式定义或“参数列表”的匹配程度如何。 There is a following definition of argument list:
参数列表有以下定义:
argument_list ::= positional_arguments ["," keyword_arguments]
["," "*" expression] ["," keyword_arguments]
["," "**" expression]
| keyword_arguments ["," "*" expression]
["," keyword_arguments] ["," "**" expression]
| "*" expression ["," keyword_arguments] ["," "**" expression]
| "**" expression
The only way I see it to be valid is for expression
to be empty, but I couldn't see how it can happen. 我认为它有效的唯一方法是
expression
为空,但我看不出它是如何发生的。
In case we assume that expression
can be empty then the following definitions should be valid: 如果我们假设
expression
可以为空,那么以下定义应该是有效的:
def foo(*)
def bar(*,**kwargs)
Those definitions don't make sense since *
requires keyword arguments after it. 这些定义没有意义,因为
*
后面需要关键字参数。
So I would appreciate any clarifications on the subject. 所以我很感激有关这个问题的任何澄清。 What do I miss?
我错过了什么? Or is the above BNF not quite correct?
或者上面的BNF不太正确?
The part of the grammar you're looking at describes function calls . 您正在查看的语法部分描述了函数调用 。 And a bare
*
is indeed invalid in a function call. 并且在函数调用中确实无效
*
。
The function definition grammar is in another part of the language reference. 函数定义语法是语言参考的另一部分。 These productions are relevant:
这些作品是相关的:
parameter_list ::= (defparameter ",")*
( "*" [parameter] ("," defparameter)* ["," "**" parameter]
| "**" parameter
| defparameter [","] )
parameter ::= identifier [":" expression]
defparameter ::= parameter ["=" expression]
Note that here, parameter
s and defparameters
are optional after after the *
. 注意,这里,
parameter
S和defparameters
后后是可选的*
。
The error that complains about def f(*)
and def f(*, **kwds)
does not come from the grammar. 抱怨
def f(*)
和def f(*, **kwds)
不是来自语法。 It's legal as far as the grammar is concerned, and is parsed successfully. 就语法而言,它是合法的,并且被成功解析。 Only during AST generation this is detected and flagged as error.
仅在AST生成期间,检测到该标记并将其标记为错误。 This isn't the only syntactical constraint that isn't handled in the grammar.
这不是语法中没有处理的唯一语法约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.