当我不小心输入时,我在交互式控制台中编写了一些 Python 代码
def f(_, ): pass
结果令我惊讶的是,口译员竟然没有提示。我实际上是想有两个伪参数,但如果第二个参数没有名称,为什么解释器会接受该函数?
请您参考如下方法:
看看 function definition syntax您可以看到函数的参数列表具有以下语法:
parameter_list ::= defparameter ("," defparameter)* ["," [parameter_list_starargs]]
| parameter_list_starargs
Which means that, after you are done with positional parameters, you can put a comma and go on with the named or starred parameters (parameter_list_starargs); but actually having those after that last comma is optional, and so it is legal to have one extra comma at the end of the list of positional parameters. Furthermore, looking at the syntax of parameter_list_starargs:
parameter_list_starargs ::= "*" [parameter] ("," defparameter)* ["," ["**" parameter [","]]]
| "**" parameter [","]
It can be seen that it is also allowed to have one extra comma after the last named parameter.
As a side syntactic note, the general syntax of a function declaration is:
funcdef ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite
Which, among other things, indicates that the annotation of a function can be any expression, rendering in fact as valid code things like:
def f(_,) -> (lambda x, y: True): pass
