简体   繁体   English

Python 语法:函数参数中的 `for`

[英]Python Syntax: `for` in function arguments

This following part is copied from the official, complete Python 3 grammar .以下部分复制自官方的完整 Python 3 语法

arglist: argument (',' argument)*  [',']

argument: ( test [comp_for] |
            test ':=' test |
            test '=' test |
            '**' test |
            '*' test )

comp_iter: comp_for | comp_if
sync_comp_for: 'for' exprlist 'in' or_test [comp_iter]
comp_for: [ASYNC] sync_comp_for
comp_if: 'if' test_nocond [comp_iter]

( arglist is used in multiple places where you'd pass arguments to a function call or class definition). arglist用于将参数传递给函数调用或类定义的多个地方)。

I am confused by the rule argument : test [comp_for] .我对规则argument : test [comp_for]感到困惑argument : test [comp_for] As . for . in .作为. for . in . . for . in . generators are already valid derivations of test , this seems to imply that a for as a function argument has a special meaning.生成器已经是test有效派生类,这似乎意味着for作为函数参数具有特殊含义。

my_function(x for x in range(3))

However, just playing around with this definition always interpreted it as the usual generator object that is created by the described syntax.然而,只是玩弄这个定义总是将它解释为由所描述的语法创建的通常的生成器对象。

y = (x for x in range(3))
my_function(y)

So, is there actually anything special about that syntax?那么,这种语法实际上有什么特别之处吗? Or is it just legacy / future reserved code?或者它只是遗留/未来的保留代码?

(x for x in range(3)) is a generator expression, which is derived from the test non-terminal. (x for x in range(3))是一个生成器表达式,它源自test非终结符。 But x for x in range(3) is not derived from test ;但是x for x in range(3)不是从test派生的; the parentheses are necessary.括号是必要的。 So without the argument : test [comp_for] production, sum((x for x in range(3))) would be a valid function call, but not sum(x for x in range(3)) .因此,如果没有argument : test [comp_for]生产, sum((x for x in range(3)))将是一个有效的函数调用,但不是sum(x for x in range(3))

On the other hand, sum(x for x in range(3)) cannot be parsed in any other way, and the syntax seems less cluttered than the version with extra parentheses.另一方面, sum(x for x in range(3))不能以任何其他方式解析,并且语法似乎没有带有额外括号的版本那么混乱。 So when generator expressions were introduced in Python 2.4, the syntax for argument lists was modified to make the syntactic sugar possible -- but only when the generator expression is the only argument.因此,当 Python 2.4 中引入生成器表达式时,修改了参数列表的语法以使语法糖成为可能——但前提是生成器表达式是唯一的参数。

You can find a longer description of the change in PEP 289 .您可以在PEP 289 中找到有关更改的详细说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM