Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need coroutines in python? [closed]

I've heard about co-routines long ago, but never used them. As I know, co-routines are similar to generators.

Why do we need co-routines in Python?

like image 667
Rainmaker Avatar asked Dec 02 '16 06:12

Rainmaker


2 Answers

Coroutines are similar to generators with a few differences. The main differences are:

  1. generators are data producers
  2. coroutines are data consumers

You may have a look here for details

like image 145
user1554295 Avatar answered Oct 09 '22 09:10

user1554295


Generator uses yield to return values. Python generator functions can also consume values using a (yield) statement. In addition two new methods on generator objects, send() and close(), create a framework for objects that consume and produce values. Generator functions that define these objects are called coroutines.

Coroutines consume values using a (yield) statement as follows:

value = (yield)

With this syntax, execution pauses at this statement until the object's send method is invoked with an argument:

coroutine.send(data)

Then, execution resumes, with value being assigned to the value of data. To signal the end of a computation, we shut down a coroutine using the close() method. This raises a GeneratorExit exception inside the coroutine, which we can catch with a try/except clause.

The example below illustrates these concepts. It is a coroutine that prints strings that match a provided pattern.

def match(pattern):
    print('Looking for ' + pattern)
    try:
        while True:
            s = (yield)
            if pattern in s:
                print(s)
    except GeneratorExit:
        print("=== Done ===")

We initialize it with a pattern, and call __next__() to start execution:

m = match("Jabberwock")
m.__next__()
Looking for Jabberwock

The call to __next__() causes the body of the function to be executed, so the line "Looking for jabberwock" gets printed out. Execution continues until the statement line = (yield) is encountered. Then, execution pauses, and waits for a value to be sent to m. We can send values to it using send().

like image 34
Wasi Ahmad Avatar answered Oct 09 '22 10:10

Wasi Ahmad