×

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 make a firewall in Python?

Firewall: The firewall is a network which controls the incoming and outgoing network traffics of a monitor. It blocks the dataset based on the set of rules written in the security...

3 minutes read.

Python program to find the GCD or HCF

Python program to find the GCD or HCF The largest positive integer that perfectly divides the two numbers is the HCF (Highest Common Factor) or GCD (Greatest Common Deviser). For example,...

5 minutes read.

Function annotations() in Python

What is Function Annotations? Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution....

3 minutes read.

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Python hasattr() function

Python hasattr() function The hasattr() function in Python returns a Boolean value ‘True’ if the given object has the specified attribute, else it returns False. Syntax hasattr(object, name) Parameter object: it is a required parameter which represents an object. attribute:...

1 minute read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

Captcha Code in Python with Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Multithreading

In python, we can implement multithreading. In this tutorial, we will understand the basics of implementing multithreading in a python programming language. Multithreading is just like multiprocessing. We use it...

4 minutes read.

Python object()

Python object() class The object class in Python is a base for all classes. It returns a new featureless object. Syntax class object Parameter NA Return It returns a new featureless object. Example 1 # Python program explaining # the object()...

1 minute read.

Exclusive OR in Python

In Python, the exclusive OR (XOR) operator is represented by the caret symbol (^). It compares each bit of the first operand to the corresponding bit of the second operand,...

3 minutes read.

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Binary Search Visualization using Pygame in Python

A calculation like Binary Search is seen effectively by picturing. Here in this tutorial, a function that pictures the Binary Search Algorithm is carried out. The Graphical User’s Interface (GUI)...

15 minutes read.

Array to String in Python

What is an Array: The idea behind an array is to group several items of the same type, making it easier to locate each element by adding an extra offset to...

4 minutes read.

Python Set issubset() method

Python Set issubset() method The set.issubset() method in Python returns True if all items in the set exists in the specified set, otherwise it returns False. Syntax set.issubset(set1) Parameter set- This parameter represents the set to check whether...

2 minutes read.

Reason for Python So Popular

One of the languages that is witnessing outstanding development and acceptance every year in Python. Python has emerged as the programming language with the greatest rate of growth, and Stack...

3 minutes read.

Python Tuple index() Method

Python Tuple index() Method The tuple.index() method of Python finds the first occurrence of the specified value and returns its index if the value is found else raises an exception if...

1 minute read.

Python and its advantages

What is Python? Python is an object-oriented programming language, a general-purpose programming language with a high level, and also an interpreted language that has an easy syntax and dynamic semantics. Python...

7 minutes read.