Introduction to Coroutines
Explore the fundamentals of Python coroutines, including their syntax, lifecycle states, and interaction patterns. Understand how coroutines enhance asynchronous programming by allowing data to be sent and received, plus learn how to manage nested generators using yield from for more efficient code execution.
We'll cover the following...
What is a coroutine?
A coroutine is syntactically like a generator. In a coroutine, the yield keyword appears at the right side of an expression. For example:
x = yield
If there’s no expression besides yield, the coroutine may or may not produce any value.
In place of using the next() method, for coroutines to receive the data, a caller calls the send() function as:
caller.send(x)
💡 Remember, no data may go in or out through the
yieldkeyword.
Bringing upgrades to Python generators led to the advent of coroutines.
Generator as a coroutine
Let’s start off with an example.
Here, we define the generator as a coroutine with yield in an expression (at line 3). We make the object cr at line 6.
The ...