列表理解和生成器表达式中的 yield

yield in list comprehensions and generator expressions

以下行为对我来说似乎相当违反直觉 (Python 3.4):

>>> [(yield i) for i in range(3)]
<generator object <listcomp> at 0x0245C148>
>>> list([(yield i) for i in range(3)])
[0, 1, 2]
>>> list((yield i) for i in range(3))
[0, None, 1, None, 2, None]

最后一行的中间值实际上并不总是 None,它们是我们 send 到生成器中的任何值,相当于(我猜)以下生成器:

def f():
   for i in range(3):
      yield (yield i)

我觉得这三行完全有用,这很有趣。 Referenceyield 只允许在函数定义中使用(虽然我可能读错了 and/or 它可能只是从旧版本复制而来)。前两行在 Python 2.7 中生成 SyntaxError,但第三行没有。

另外,好像有点奇怪

有人可以提供更多信息吗?

Note: this was a bug in the CPython's handling of yield in comprehensions and generator expressions, fixed in Python 3.8, with a deprecation warning in Python 3.7. See the Python bug report and the What's New entries for Python 3.7 and Python 3.8.

生成器表达式、集合和字典理解被编译为(生成器)函数对象。在 Python 3 中,列表理解得到相同的处理;它们本质上都是一个新的嵌套范围。

如果您尝试反汇编生成器表达式,您会看到这一点:

>>> dis.dis(compile("(i for i in range(3))", '', 'exec'))
  1           0 LOAD_CONST               0 (<code object <genexpr> at 0x10f7530c0, file "", line 1>)
              3 LOAD_CONST               1 ('<genexpr>')
              6 MAKE_FUNCTION            0
              9 LOAD_NAME                0 (range)
             12 LOAD_CONST               2 (3)
             15 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             18 GET_ITER
             19 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             22 POP_TOP
             23 LOAD_CONST               3 (None)
             26 RETURN_VALUE
>>> dis.dis(compile("(i for i in range(3))", '', 'exec').co_consts[0])
  1           0 LOAD_FAST                0 (.0)
        >>    3 FOR_ITER                11 (to 17)
              6 STORE_FAST               1 (i)
              9 LOAD_FAST                1 (i)
             12 YIELD_VALUE
             13 POP_TOP
             14 JUMP_ABSOLUTE            3
        >>   17 LOAD_CONST               0 (None)
             20 RETURN_VALUE

上面显示生成器表达式被编译为代码对象,作为函数加载(MAKE_FUNCTION 从代码对象创建函数对象)。 .co_consts[0] 引用让我们看到为表达式生成的代码对象,它使用 YIELD_VALUE 就像生成器函数一样。

因此,yield 表达式在该上下文中起作用,因为编译器将它们视为伪装函数。

这是一个错误; yield 在这些表达式中没有位置。 Python grammar before Python 3.7 允许它(这就是代码可编译的原因),但 yield expression specification 表明使用 yield 这里实际上应该不起作用:

The yield expression is only used when defining a generator function and thus can only be used in the body of a function definition.

这已被确认为 issue 10544. The resolution of the bug is that using yield and yield from will raise a SyntaxError in Python 3.8; in Python 3.7 it raises a DeprecationWarning to ensure code stops using this construct. You'll see the same warning in Python 2.7.15 and up if you use the -3 command line switch 启用 Python 3 个兼容性警告的错误。

3.7.0b1 警告如下所示;将警告变成错误会给你一个 SyntaxError 异常,就像你在 3.8:

>>> [(yield i) for i in range(3)]
<stdin>:1: DeprecationWarning: 'yield' inside list comprehension
<generator object <listcomp> at 0x1092ec7c8>
>>> import warnings
>>> warnings.simplefilter('error')
>>> [(yield i) for i in range(3)]
  File "<stdin>", line 1
SyntaxError: 'yield' inside list comprehension

列表推导式中的 yield 和生成器表达式中的 yield 之间的差异源于这两个表达式实现方式的差异。在 Python 3 中,列表理解使用 LIST_APPEND 调用将堆栈顶部添加到正在构建的列表中,而生成器表达式则生成该值。添加 (yield <expr>) 只是将另一个 YIELD_VALUE 操作码添加到:

>>> dis.dis(compile("[(yield i) for i in range(3)]", '', 'exec').co_consts[0])
  1           0 BUILD_LIST               0
              3 LOAD_FAST                0 (.0)
        >>    6 FOR_ITER                13 (to 22)
              9 STORE_FAST               1 (i)
             12 LOAD_FAST                1 (i)
             15 YIELD_VALUE
             16 LIST_APPEND              2
             19 JUMP_ABSOLUTE            6
        >>   22 RETURN_VALUE
>>> dis.dis(compile("((yield i) for i in range(3))", '', 'exec').co_consts[0])
  1           0 LOAD_FAST                0 (.0)
        >>    3 FOR_ITER                12 (to 18)
              6 STORE_FAST               1 (i)
              9 LOAD_FAST                1 (i)
             12 YIELD_VALUE
             13 YIELD_VALUE
             14 POP_TOP
             15 JUMP_ABSOLUTE            3
        >>   18 LOAD_CONST               0 (None)
             21 RETURN_VALUE

字节码索引 15 和 12 处的 YIELD_VALUE 操作码分别是额外的,巢中的布谷鸟。因此,对于 list-comprehension-turned-generator,每次都有 1 yield 产生堆栈顶部(用 yield return 值替换堆栈顶部),对于生成器表达式变体你 yield 栈顶(整数),然后再次 yield ,但现在栈包含 yield 的 return 值,你得到 None第二次。

对于列表理解,预期的 list 对象输出仍然是 returned,但是 Python 3 将其视为生成器,因此 return 值为而是附加到 StopIteration exception 作为 value 属性:

>>> from itertools import islice
>>> listgen = [(yield i) for i in range(3)]
>>> list(islice(listgen, 3))  # avoid exhausting the generator
[0, 1, 2]
>>> try:
...     next(listgen)
... except StopIteration as si:
...     print(si.value)
... 
[None, None, None]

那些 None 对象是来自 yield 表达式的 return 值。

并再次重申这一点;同样的问题也适用于 Python 2 和 Python 3 中的字典和集合理解;在 Python 2 中,yield return 值仍然添加到预期的字典或集合对象中,并且 return 值是 'yielded' 最后而不是附加到StopIteration 异常:

>>> list({(yield k): (yield v) for k, v in {'foo': 'bar', 'spam': 'eggs'}.items()})
['bar', 'foo', 'eggs', 'spam', {None: None}]
>>> list({(yield i) for i in range(3)})
[0, 1, 2, set([None])]