当Python yield语句没有表达式时会发生什么? [英] What happens when a Python yield statement has no expression?

查看:116
本文介绍了当Python yield语句没有表达式时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm a C# programmer trying to understand some Python code. The code in question is a generator function, and looks like this:

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

如果我正确理解这一点,它将生成一个具有一个成员的可迭代序列.但是,yield语句后没有表达式.这种无表达式的语句应该产生什么?是否有任何使用这种编码方式的Python习惯用法?

If I understand this correctly, this will generate a iterable sequence with one member. However, there is no expression after the yield statement. What is such an expression-less statement supposed to yield? Are there any Python idioms that make use of this way of coding?

推荐答案

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

It'll yield None; just like an empty return expression would:

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

您将使用它来暂停代码.第一次在生成器上调用next()时,运行yield之前的所有内容,仅当再次调用next()时,运行yield之后的所有内容:

You'd use it to pause code. Everything before the yield is run when you first call next() on the generator, everything after the yield is only run when you call next() on it again:

>>> 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是什么,只是在该点暂停了该功能.

I used the two-argument form of next() to ignore the StopIteration exception thrown. The above doesn't care what is yielded, only that the function is paused at that point.

对于一个实际示例, @contextlib.contextmanager装饰器完全希望您以这种方式使用yield;您可以可选地 yieldwith ... as目标中使用的对象.关键是,yield之前的所有内容都是在输入上下文时运行的,而yield之后的所有内容都是在退出上下文时运行的.

For a practical example, the @contextlib.contextmanager decorator fully expects you to use yield in this manner; you can optionally yield an object to use in the with ... as target. The point is that everything before the yield is run when the context is entered, everything after is run when the context is exited.

这篇关于当Python yield语句没有表达式时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆