【问题标题】:Which syntax rule matches the def foo(a, *, b=10) compound statement?哪个语法规则匹配 def foo(a, *, b=10) 复合语句?
【发布时间】:2016-01-18 11:15:43
【问题描述】:

函数定义中参数的The formal syntax如下:

parameter_list ::=  (defparameter ",")*                                        #[1]
                    | "*" [parameter] ("," defparameter)* ["," "**" parameter] #[2]
                    | "**" parameter                                           #[3]
                    | defparameter [","] )                                     #[4]

(为清楚起见,我添加了#[num])

Where |, according to the notation, indicates alternatives.

我看不出它与以下函数定义的匹配程度:

def foo(a, *, b=10): pass

假设def foo(a, *, b=10) 形式的定义属于#[2] 的明显规则,它允许* 表示法分隔仅关键字参数。

但我认为foo 的规则必须是#[1] 和#[2] 的组合:

parameter_list ::= (defparameter ",")* "*" [parameter] ("," defparameter)* ["," "**" parameter] 

由于规则 #[1] 和 #[2] 似乎并不能单独匹配这种情况。

我在这里错过了什么?

【问题讨论】:

  • 你在下面阅读了吗? 如果一个参数有一个默认值,那么直到“*”之前的所有参数也必须有一个默认值—— 这是一个语法限制,没有被语法表达。
  • 这不是简单地说明def foo(*, a, b=10)形式的调用是非法的吗?
  • 看起来是错的,除非我也遗漏了什么。最后一个右括号没有对应的左括号。
  • @Jim 有趣。我不确定,但我想它一定是#2。 (等待答复)
  • 哦该死的,世界将走向何方?文档中的错别字!

标签: python python-3.x syntax


【解决方案1】:

正式语法似乎缺少左括号。最后一个关闭的不匹配任何东西,如果你看一下the Python 2 version,它是完全有道理的:

parameter_list ::=  (defparameter ",")*
                    (  "*" identifier ["," "**" identifier]
                    | "**" identifier
                    | defparameter [","] )

所以读成这样:

parameter_list ::=  (defparameter ",")*
                    ( "*" [parameter] ("," defparameter)* ["," "**" parameter]
                    | "**" parameter
                    | defparameter [","] )

可能有人在重新调整事物时将 ( 替换为 |。

【讨论】:

  • 我会尝试在早上提交一个问题......但是问题跟踪器无法搜索......
  • 是的,这确实很有意义。如果他们最终回复了,请尽量记住将其添加到您的答案中。
【解决方案2】:

嗯,正如 Ryan 指出的那样,这绝对看起来像一个文档错误。

对于 Python v3.5.0 中的 function declaration syntax,这是实际语言语法的定义方式

funcdef: 'def' NAME parameters ['->' test] ':' suite

parameters: '(' [typedargslist] ')'

typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])*
    [',' ['*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] | '**' tfpdef [',']]]
  | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
  | '**' tfpdef [','])

这里,tfpdef is the identifier

tfpdef: NAME [':' test]

而test 与expression 相同

test: or_test ['if' or_test 'else' test] | lambdef

【讨论】:

    猜你喜欢
    • 2011-03-26
    • 2016-04-27
    • 2021-12-11
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 2011-01-14
    相关资源
    最近更新 更多