×

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 Install PIP In Python

How to Install PIP In Python The libraries for Python have made our work easier than we expected. From a simple addition of two numbers to applying algorithms on the big...

4 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

Python Key Error

What is an Error? Errors are nothing but problems in the program which occur in a program code, and this will stop the execution of the program. It is also called...

6 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Gaussian elimination in python

Linear and polynomial equations are used in almost all fields of numerical simulation. However, its most common use in engineering is in the area of linear system analysis. The broader...

3 minutes read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

Python list() | List class in Python

The list() class in Python creates a list object where the list object is a collection which is ordered and changeable. Syntax class list([iterable]) Parameter Iterable: It is a required parameter which represents a sequence, collection...

1 minute read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Is Python Object Oriented Programming language

In this tutorial, we will see whether python also belongs to an object-oriented programming language like several others. We will also see the advantages of using OOPs. Further, we will...

4 minutes read.

Adding a key-value pair to dictionary in Python

Python dictionaries are collections of unsorted key-value pairs. This article will examine a method for adding new key-value teams to an existing dictionary. Dictionary in Python With the aid of curly brackets...

3 minutes read.

Python callable() Function

Python callable() Function The callable() function returns a boolean value ‘True’ if the specified object is callable, else it returns False. Syntax callable(object) Parameter Object:  The object parameter represents the value to test if it is callable...

1 minute read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.

Arithmetic Expressions in Python

What is Python Expression? Expressions are collections of operands and operators. Python expressions are translated by the Python interpreter into some value or outcome. In Python, an expression is made up...

13 minutes read.

Python coding platform

Python is a popular general-purpose programming language with many applications. High-level data structures, datatypes, dynamic binding, and many other features make it useful for both designing complex applications and "glue...

6 minutes read.

Python JSON Schema

Python-jsonschema JSON: JSON stands for JavaScript Object Notation. It is a text-based format that represents structured data and can be used to interchange data among various applications. This is self-defining language...

5 minutes read.

Python Pascal Triangle

Python Pascal Triangle Pascal triangle A pascal triangle is a number pattern of triangular array of the binomial coefficients. For designing a pascal triangle, we write a function in the program which...

5 minutes read.

Python Continue Statement

In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the...

3 minutes read.

List Subtract in Python

The List is one of the most unique Data Structures in Python. It is generally used to store multiple values in just one single variable. It is one of the...

4 minutes read.

Python ord() Function

Python ord() Function The ord() function in Python returns the number representing the Unicode code of a specified character. Syntax ord(c) Parameter c: This parameter represents a string or any character. Return This function returns the number...

1 minute read.