Overview:
-
The yield statement returns a value back to the caller and gets suspended.
-
The send() method, sends values into the current yield statement which is in suspended state, resumes the generator function and returns the values from the next yield.
-
The new values sent to the yield as it resumes should be assigned to variables in order to use them. If not assigned, the values are simply lost.
- In the Python statement below, the values sent by send() are recieved by the variables in the yield expression, which are assigned further to use them inside the generator function. Without this assignment, the values sent by send() are lost.
a,b = yield a, b |
- The statement below does not store the values sent by send(). The send() does not work like, the variables used in the yield are replaced with the values sent by send() within the whole scope of the generator function. Explicit storage of values from yield is essential.
yield a, b |
Example:
# Define a generator function while(a > 0): print("####Inside gen() - begin####") # Create a generator iterator # Start the generator print("Callee doing something else - Gen still frozen") # Send values to generator as packed in a tuple # Uncommenting the print below will lead to, # Uncommenting the print below will lead to, |
Output:
<class 'generator'> ####Inside gen() - begin#### 9 19 100 ####Inside gen() - end#### Generator Just before suspend (9, 19) Callee doing something else - Gen still frozen Callee doing still more - Gen frozen all the time Generator resumed ####Inside gen() - begin#### 29 39 100 ####Inside gen() - end#### Generator Just before suspend (29, 39) |