Python Coroutine
Introduction
In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state.
Coroutines and generates are similar but coroutines consist of extra methods and the use of yield statements is changed. The iteration data is produced by the generators while the coroutines consume the data and it works as an extension of generators.
- In Python, Both the generators and the coroutines work similarly. They work over the data. In simple words, Generators producethe data, and Coroutines consume the data.
- The execution of a function (coroutine functions) can be suspended at a specific point, and then later, the execution can be resumed from that same point whenever it needs to be resumed.
- In Python, By using the yield keyword we can stop the execution of a function. yield can also be used as an expression.
line = (yield)
Yield expression captures and returns the value of whatever we send to the coroutine.
Example 1:
def bare_bones():
print("1st Coroutine!")
while True:
value = (yield)
print(value)
Output:
coroutine = bare_bones()
Example 2:
def print_name(prefix):
print("Searching prefix:{}".format(prefix))
while True:
name = (yield)
if prefix in name:
print(name)
corou = print_name("Tutorial")
# Execution of coroutine will start
corou.__next__()
# inputs sending
corou.send("JavaTpoint")
corou.send("Tutorial JavaTpoint")
Output:
Searching prefix: Tutorial
Tutorial JavaTpoint
Arguments Passing
We can also pass arguments to coroutines because coroutines can also be able for receiving arguments like functions.
Example:
def filter_line(num):
while True:
line = (yield)
if num in line:
print(line)
cor = filter_line("45")
next(cor)
cor.send("Karan, age:21")
cor.send("Jhon, age:45")
cor.send("Lucifer, age:29")
Output:
Jhon, age:45
Using Multiple Breakpoints
We can apply multiple yield statements together in the same separate coroutine.
Example:
def joint_print():
while True:
part_1 = (yield)
part_2 = (yield)
print("{} {}".format(part_1, part_2))
cor = joint_print()
next(cor)
cor.send("Tutorial")
cor.send("and Examples")
Output:
Tutorial and Examples
StopIteration Exception
Calling send() function once more will create a StopIteration exception.
Example:
def test():
while True:
value = (yield)
print(value)
try:
cor = test()
next(cor)
cor.close()
cor.send("Great")
except StopIteration:
print("This is the best tutorial")
Output:
This is the best tutorial
Closing a Coroutine
Coroutine may run endlessly, the close() method is used for closing the coroutine. GeneratorExit exception is generated when the coroutine is closed and then the stopIteration exception is raised if we want to send values.
Example:
def print_name(prefix):
print("Searching prefix:{}".format(prefix))
try :
while True:
name = (yield)
if prefix in name:
print(name)
except GeneratorExit:
print("Closing coroutine!!")
corou = print_name("Tutorial")
corou.__next__()
corou.send("Javatpoint")
corou.send("Tutorial JavaTpoint")
corou.close()
Output:
Searching prefix: Tutorial
Tutorial JavaTpoint
Closing coroutine!!
Creating Pipelines
A pipeline can be defined as a sequence of processing elements arranged then the output of every element is the input of the next element.
Coroutines are using for setting pipes. coroutines can be chained together and data is pushed through the pipe by using send() method.
Each pipeline needs at least one source and one sink.
The leftover steps of the pipe can execute various operations, from filtering to transforming, routing, and diminishing data.

Example:
# Code for coroutine chaining
def producer(sentence, next_coroutine):
tokens = sentence.split(" ")
for token in tokens:
next_coroutine.send(token)
next_coroutine.close()
def pattern_filter(pattern="ing", next_coroutine=None):
# pattern searching and sending it to print_token() for printing
print("Searching for {}".format(pattern))
try:
while True:
token = (yield)
if pattern in token:
next_coroutine.send(token)
except GeneratorExit:
print("Filtering Done!!")
def print_token():
print("This is sink and It will print tokens")
try:
while True:
token = (yield)
print(token)
except GeneratorExit:
print("Prininting Done!")
pt = print_token()
pt.__next__()
pf = pattern_filter(next_coroutine = pt)
pf.__next__()
sentence = "This is the best Python tutorial"
producer(sentence, pf)
Output:
This is sink and It will print tokens
Searching for ing
running
moving
Filtering Done!!
Printing Done!
Conclusion
As you have seen above article is based on Python Coroutines. You have learned the concept of Coroutines in Python and learned how to perform coroutines operations in Python.