What happens when the Python yield statement has no expression?

I am a C # programmer who is trying to understand Python code. This code is a generator function and looks like this:

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

If I understand this correctly, this will lead to a repeated sequence with one member. However, there is no expression after the yield statement. What is an expression without expressions that must yield? Are there any Python idioms that use this encoding method?

+6
source share
1 answer

This will give None ; just like an empty return :

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

You can use it to pause the code. Everything before yield starts when the next() call is made on the generator, everything after yield starts only when next() called 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 a form with two next() arguments to ignore the StopIteration exception. The above does not care about yield ed, only that the function is suspended at this point.

For a practical example, @contextlib.contextmanager decorator fully expects to use yield this way; you can optionally yield object to be used with ... as . The fact is that everything that was before yield starts when the context is entered, everything after launch when the context is exited.

+9
source

All Articles