What happens when a Python yield statement has no expression?

柔情痞子 提交于 2019-12-01 16:21:07

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

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

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!