Why “Yield” Is an Excellent Python Keyword — Generators and Coroutines
Suspend and Resume Execution in Coroutines

Note: It’s important to know that Python is phasing out the use of generators as the basis for coroutines. Check the official documentation. However, the concept of coroutines can be easy to understand if we know that yield has the meaning of “giving way.”

In this usage, it’s applicable to yield ’s second meaning: give way. It’s pretty much like the traffic “yield” sign in real life. You temporarily stop your vehicle such that other vehicles with right of the way can go first. Applying this analog to programming, it’s the basic idea of coroutines.

As you can see, the key to coroutines is that the execution is suspended temporarily and it can be resumed later on when it’s applicable. Doesn’t this sound familiar to you? The generator function runs and yields the element (the execution is suspended), and when the next element is requested, it continues to run from where it was suspended (the execution is resumed).

Actually, we can use the yield keyword to implement a coroutine. Let’s see the following code snippet for a simple example:

We first define a coroutine function using the yield keyword. As you can see, the overall structure is similar to the generator function. However, you’ll notice that the yield keyword appears after the assignment operator (i.e. the equals sign).

keyword. As you can see, the overall structure is similar to the function. However, you’ll notice that the keyword appears after the assignment operator (i.e. the equals sign). The assignment is possible because, in addition to the typical next() function that works with a generator, generators also support the send() function.

function that works with a generator, generators also support the function. In the example, we send a string data (i.e. “Here’s the data that your requested.” ) back to the coroutine. Specifically, the data that we sent is set to the variable x , and we’re able to print the x value as expected.

) back to the coroutine. Specifically, the data that we sent is set to the variable , and we’re able to print the value as expected. The StopIteration exception is expected because the generator function has reached the end, which is consistent with the behavior of a generator (as shown in the last section).
['Yong Cui']
['Python', 'Technology', 'Software Engineering', 'Artificial Intelligence', 'Programming']