Coroutine in Python

Counters | Loops | Python Methods and Functions

We are all familiar with function which is also known as subroutine , procedure , subprocess , etc. . Function — it is a sequence of instructions packaged as a unit to perform a specific task. When the logic of a complex function is divided into several separate steps that are themselves functions, then these functions are called helper functions or routines .

Routines in Python are called by the main function, which is responsible for coordinating the use of these routines. Routines have a single entry point.

Coroutines are generalizations of subroutines. They are used for collaborative multitasking, where a process voluntarily gives control periodically or in standby mode to allow multiple applications to run concurrently. Difference between coroutine and subroutine:

  • Unlike subroutines, coroutines have many entry points to pause and resume execution. A coroutine can suspend its execution and transfer control to another coroutine, and can resume execution where it left off.
  • Unlike subroutines, there is no main function to call coroutines in a specific order and coordinate results. Coroutines are cooperative, which means they are chained together to form a pipeline. One coroutine can consume input and send to others who process it. Finally, there could be a coroutine to display the result.

Coroutine Vs Thread

Now you might be thinking how a coroutine is different from threads, both seem to do the same job. 
In the case of threads, this is the operating system (or runtime) that switches between threads according to the scheduler. Although in the case of coroutines, it is the programmer and programming language that decides when to switch coroutines. Coroutines work together multitasking, pausing and resuming at specified points by the programmer.

Python Coroutine

In Python, coroutines are similar to generators, but with a few extra methods and a slight change in how we use the

# Python3 demo program
# coroutine execution

 

def print_name (prefix):

print ( "Searching prefix: {}" . format (prefix))

while True :

  name = ( yield )

if prefix in name:

print (name)

  
# call the coroutine, nothing happens

corou = print_name ( "Dear" )

 
# This will start execution of the coroutine and
# Prints the first line & quot; Searchig prefix ... & quot;
# and move execution to the first yield statement
corou .__ next __ ()

  
# sending inputs

corou.send ( "Atul" )

corou.send ( "Dear Atul" )

Output:

 Searching prefix: Dear Dear Atul 

Coroutine execution

Execution of a coroutine is similar to a generator. When we call the coroutine, nothing happens, it runs only in response to the next () and send () methods. This is clearly seen in the example above, since only after calling the __next __ () method, our coroutine starts executing. After this call, execution jumps to the first yield expression, now execution pauses and waits for the value to be passed to the object. When the first value is sent to it, it checks the prefix and prints the name if the prefix is ​​present. After printing the name, it loops through until it encounters the expression again.

Closing a coroutine

A coroutine can run indefinitely, using the close () . When the coroutine closes, it throws a GeneratorExit exception that can be caught in the usual way. After the coroutine is closed, if we try to send values, this will raise a StopIteration exception. Below is a simple example:

# Python3 demo program
# close the coroutine

 

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 ( " Dear " )

corou .__ next __ ()

corou.send ( " Atul " )

corou.send ( "Dear Atul" )

corou.close ()

Exit :

 Searching prefix: Dear Dear Atul Closing coroutine !! 

Chained coroutines to create a pipeline

Coroutines can be used to set pipes. We can chain coroutines together and send data through the pipe using the send () method. The pipe needs:

    • Original source (manufacturer) that outputs the entire pipe. The producer is usually not a coroutine, it's just a simple method.
    • Sink which is the end point of the pipe. The sink can collect all the data and display it.

Below is a simple example of chaining:

# Python3 demo
# chaining coroutine

 

def producer (sentence, next_coroutine):

  " ""

A maker that just separates lines and

  pass it to the pattern_filter coroutine

  " ""

tokens = sentence.split ( "" )

for token in tokens:

  next_coroutine.send (token)

next_coroutine.close ()

  

def pattern_filter (pattern = "ing" , next_coroutine = None ):

"" "

  Search for a template in the received token

and if a template was found, submit it

print_token () print coroutine

"" "

  print ( "Searchin g for {} " . format (pattern))

try :

while True :

token = ( yield )

if pattern in token:

next_coroutine.send (token)

except GeneratorExit:

  print ( " Done with filtering !! " )

 

def print_token ():

"" "

  Act as a sink, just print

received tokens

"" "

  print ( "I'm sink, i'll print tokens" )

try :

  while True :

token = ( yield )

  print (token)

except GeneratorExit:

print ( "Done with printing!" )

 

pt = print_token ()

pt .__ next __ ()

pf = pattern_filter (next_coroutine = pt)

pf .__ next __ ()

 

sentence = "Bob is running behind a fast moving car"

producer (sentence, pf)

Output:

 I'm sink, i'll print tokens Searching for ing running moving Done with filtering !! Done with printing! 

Links

This article courtesy of Atul Kumar . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.