Why do we need coroutines in python? [closed]

北战南征 提交于 2019-12-22 08:07:55

问题


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?


回答1:


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().




回答2:


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



来源:https://stackoverflow.com/questions/40925797/why-do-we-need-coroutines-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!