×

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

Python Rest API

In this tutorial, we will understand the meaning of API and REST API. We will understand the working of REST API. We will then realize the boundaries of architecture defined...

4 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

Arguments and parameters in Python

Generally, there is a misunderstanding that parameters and arguments, both are the same. But, as a programmer, you need to understand the difference between these two. Parameters: While defining a function, we...

5 minutes read.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

Assignment Operators in Python

The prime usage of Assignment Operators is to assign values to variables. These are taken into account to do operations on values and variables. There are some special symbols in python...

4 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

Python Selectors

Python: 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 faster way....

4 minutes read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

Find Words in String Python

Python : Python programming language is considered a general purpose; it is a high-level programming language that is not much difficult but easier to learn. Python programming language is rich in...

5 minutes read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Tuple in Python

Tuples Tuples are the same as the list but as we know that lists are mutable means we can change the data from it. In the tuple we cannot change the...

6 minutes read.

How to reverse a string in python

How to reverse a string in python A Brief About Strings- The String is a data type in Python that has a sequence of characters. This series of characters are represented in...

4 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Simple GUI calculator using PyQt5 in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

4 minutes read.

Python String Methods

Python String Methods Python has a set of built-in string methods. The Python string methods are as follows: capitalize() The string.capitalize() method returns a copy of the string by converting the...

5 minutes read.

An Introduction to Mocking in Python

Python Mocking is a testing library. It enables you to substitute portions of your system under test with fake(mock) objects and make assertions about how they were utilized.  The test is...

3 minutes read.