Generator-based coroutine versus native coroutine

江枫思渺然 提交于 2019-11-30 20:10:12

There is no functional difference. "Native coroutines" using the async and await keywords are just syntactic sugar for what was previously implemented in "generator-based coroutines."

The use of async and await is recommended in the 3.5 docs if there is no need to support older Python versions.

To expand on what Mike S wrote: native coroutines in CPython share most of the same code as generators, so there's little functional difference. However, I think that PEP-492 rises above the threshold of just "syntactic sugar". Generators and native coroutines have separate purposes, so the new syntax clarifies an author's intent and can do things the old syntax cannot. Here are some examples:

  • Generators are iterable, and native coroutines are not.
  • Native coroutines also permit new syntaxes like async context managers and async iterators.
  • Coroutines have useful debugging messages, e.g. a warning if you never await a coroutine object.

The new syntax also nicely mirrors the asyncio library and resembles keywords used in other languages.

Well, conventionally the way to write coroutines involved callbacks. Even though callbacks might be convenient initially, but in my opinion, they lead to highly complicated and complex code, which is not pythonic to say the least. Besides, yield (especially yield from since python 3.3), has made implementing coroutines a lot easier and pythonic.

With generators, you can easily divide your code into initial part and callbacks.

@asyncio.coroutine
def print_sum(x, y):
    result = yield from compute(x, y)

    #write callback code
    print("%s + %s = %s" % (x, y, result))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!