python - 当 Python yield 语句没有表达式时会发生什么?

标签 python generator yield

我是一名试图理解一些 Python 代码的 C# 程序员。有问题的代码是一个生成器函数,看起来像这样:

def func():
    oldValue = curValue
    yield
    curValue = oldValue

如果我理解正确,这将生成一个包含一个成员的可迭代序列。但是,yield 语句后没有表达式。这样一个没有表达式的语句应该产生什么?有没有使用这种编码方式的 Python 习语?

最佳答案

它将产生None;就像一个空的 return 表达式会:

>>> def func():
...     yield
... 
>>> f = func()
>>> next(f) is None
True

您可以使用它来暂停代码yield 之前的所有内容在您首次调用生成器上的 next() 时运行,yield 之后的所有内容仅在您调用 时运行>next() 再次:

>>> def func():
...     print("Run this first for a while")
...     yield
...     print("Run this last, but only when we want it to")
... 
>>> f = func()
>>> next(f, None)
Run this first for a while
>>> next(f, None)
Run this last, but only when we want it to

我使用了 next() 的双参数形式来忽略抛出的 StopIteration 异常。上面的代码不关心 yield 是什么,只关心函数在那一点暂停。

举个实际例子,@contextlib.contextmanager decorator完全希望您以这种方式使用 yield;您可以可选 yield 一个对象以在with ... as 目标中使用。重点是进入上下文时运行 yield 之前的所有内容,退出上下文时运行之后的所有内容。

关于python - 当 Python yield 语句没有表达式时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22960397/

相关文章:

python - 列出Python包中同名的方法

python - google app engine - ndb 查询只获取 python 中的几列

python - 无法在 jupyter 笔记本中导入 psycopg2,但可以在 python3 控制台中导入

不使用 yield 的 python 生成器无尽的流

python 3 : How to generate a pseudo-random sequence per object?

Python 意外的 StopIteration

python - 使用带有生成器函数的 python 多处理模块时出错。

python - 使用 MySQLdb 插入 MySQL - python

typescript :使用来自 redux-saga 的 call() 类型

reactjs - 如何在 React 中使用 Yield 关键字?