SoFunction
Updated on 2024-11-15

A brief look at python yield usage with examples

The example code is as follows

def demo():
  print("Begin execution...")
  while 1:
    res = yield 'This is the return value'
    print("res:",res)
d1 = demo()
print(d1)
print(next(d1))
print("*"*20)
print(next(d1))

The results of the implementation are as follows:

carry out sth.
This is the return value
********************
res: None
This is the return value

Code explanation, personal understanding, I hope to be able to point out if I'm wrong:

d1 = demo(); generates an object that doesn't output anything

print(d1); here do not enter any content, because the program pauses the first time it encounters a field, even if there is an output statement in front of the field, as well as to the output

print(next(d1)); the program will then continue execution of the yield, the second encounter yield, return "This is the return value", add up the output will start executing ...
This is the return value

print(next(d1)); execute next(d1) again, the equivalent of the third encounter yield, because the previous step is equivalent to being return, res does not assign a value, so None, continue to execute while, the fourth encounter yield, the output is "this is the return value".

This is the whole content of this article.