9

I just read PEP0492 talking about the new approach on coroutines but the PEP failed to make me understand the difference between generator-based coroutines and native ones. Can someone tell me the difference (maybe with examples)?

For what I understood they uses different words (yield/yield from and await/async/yield). I understand that at the end of a native coroutine a yield is expected, but this also stands true for generator-based ones.

4

3 回答 3

10

扩展 Mike S 所写的内容:CPython 中的原生协程与生成器共享大部分相同的代码,因此在功能上几乎没有区别。但是,我认为 PEP-492 超出了“语法糖”的门槛。生成器和原生协程有不同的用途,因此新语法阐明了作者的意图,并且可以做旧语法不能做的事情。这里有些例子:

  • 生成器是可迭代的,而原生协程则不是。
  • 原生协程还允许使用异步上下文管理器和异步迭代器等新语法。
  • 协程具有有用的调试消息,例如,如果您从未await使用协程对象,则会发出警告。

新语法也很好地反映了asyncio库,类似于其他语言中使用的关键字。

于 2017-03-01T13:44:41.780 回答
3

没有功能上的区别。async使用and关键字的“原生协程”await只是之前在“基于生成器的协程”中实现的语法糖。

如果不需要支持较旧的 Python 版本,建议在3.5 文档中使用asyncand 。await

于 2015-12-04T10:19:45.640 回答
0

好吧,通常编写协程的方式涉及回调。尽管回调最初可能很方便,但在我看来,它们会导致高度复杂和复杂的代码,至少可以说这不是 Pythonic。此外,yield(尤其是yield from从 python 3.3 开始),实现协程变得更加容易和 pythonic。

使用生成器,您可以轻松地将代码划分为初始部分和回调。

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

    #write callback code
    print("%s + %s = %s" % (x, y, result))
于 2015-09-15T09:44:27.707 回答