为什么在生成器中的 yield 调用周围添加括号允许它 compile/run?

Why does adding parenthesis around a yield call in a generator allow it to compile/run?

我有一个方法:

@gen.coroutine
def my_func(x):
    return 2 * x

基本上,一个龙卷风协程。

我正在列一个清单,例如:

my_funcs = []
for x in range(0, 10):
    f = yield my_func(x)
    my_funcs.append(x)

在试图使它成为一个列表理解时,例如:

my_funcs = [yield my_func(i) for i in range(0,10)]

我意识到这是无效的语法。它 turns out you can do this 使用 () 左右收益率:

my_funcs = [(yield my_func(i)) for i in range(0,10)]

Python 2.7.11 OSX。此代码确实需要在两个 Python2/3 中工作,这就是为什么上面的列表理解不是一个好主意(请参阅 了解为什么,上面的列表 comp 在 Python 2.7 中工作但已损坏在 Python 3).

yield 表达式必须在任何上下文中括起来,除非作为整个语句或作为赋值的右侧:

# If your code doesn't look like this, you need parentheses:
yield x
y = yield x

这在 PEP that introduced yield expressions (as opposed to yield statements), and it's implied by the contexts in which yield_expr appears in the grammar 中有说明,虽然没有人期望您阅读语法:

A yield-expression must always be parenthesized except when it occurs at the top-level expression on the right-hand side of an assignment.