×

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.

Python Coroutine

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.


Related Topics

How to Convert A List into String In Python?

How to Convert A List into String In Python? List is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets...

3 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.

STL in Python

Python has many libraries that are very useful and simplify many complex codes. In the same way, STL is also one of the python libraries used for reading and writing...

3 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

Python Linear regression

In this tutorial, we will understand the meaning, usage, and types of Linear Regression. Further, we will comprehend the terms cost function and Optimization. Linear Regression is the widely used Machine...

3 minutes read.

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

Python pow() Function

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

Python divmod() function

Python divmod() function The divmod() function in Python returns a tuple containing the quotient  and the remainder when parameter ‘a’ (divident) is divided by parameter ‘b’ (divisor). Syntax: divmod(a, b) Parameter a: This parameter represents a number you...

1 minute read.

Python Typing Module

An Introduction to the Typing Module The typing module is introduced in Python version 3.5 and used to provide hinting method types in order to support static type checkers and linters...

10 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python data science course

What is meant by Data Science? When processing raw, structured, and unstructured data utilizing various technologies, algorithms, and the scientific method, data science is a detailed study of the enormous quantity...

4 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Curdir Python

Python Programming Language Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Python Abstract Class

An Introduction to Abstract Classes An Abstract Class is one of the most significant concepts of Object-Oriented Programming (OOP). An Abstract class can be deliberated as a blueprint or design for...

6 minutes read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

Python Online Compiler

Compose, Run and Offer Python code internet involving OneCompiler's Python online compiler free of charge. It's one of the hearty, highlight-rich web-based compilers for python language, supporting both the adaptations, which...

3 minutes read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

Character Set in Python

A collection of legal characters that will recognize by a programming language known as a Character set. Taking python programming language as an instance. The set of characters supported by the...

6 minutes read.