...

/

Introduction to Coroutines

Introduction to Coroutines

Learn how to evolve coroutine from a generator.

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.

Press + to interact
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 ...