Search⌘ K
AI Features

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.

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 yield keyword.

Bringing upgrades to Python generators led to the advent of coroutines.

Generator as a coroutine

Let’s start off with an example.

Python 3.10.4
def coroutine():
print('Started')
x = yield # yield with an expression
print('Recieved',x)
cr = coroutine()
next(cr) # Activating coroutine
cr.send('Educative') # Sending value to coroutinne

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 ...