Skip to main content
 首页 » 编程设计

python之这两种基于生成器的协程是同一个概念吗

2025年05月04日25leader

似乎有两种基于生成器的协程:

  1. 来自 a reply 作者:Jim Fasarakis Hilliard:

    Generator-based coroutine: A generator (def + yield) that is wrapped by types.coroutine . You need to wrap it in types.coroutine if you need it to be considered a coroutine object.

  2. 摘自 Python in a Nutshell,未明确调用它 “基于生成器的协程”:

    When you write Python code based on asyncio (ideally also using add-on modules from asyncio.org), you’ll usually be writing coroutine functions. Up to Python 3.4 included, such functions are generators using the yield from statement covered in “yield from (v3-only)” on page 95, decorated with @asyncio.coroutine , covered in “asyncio coroutines” on page 518;

    来自 https://www.python.org/dev/peps/pep-0492/#differences-from-generators

    generator-based coroutines (for asyncio code must be decorated with @asyncio.coroutine)

    http://masnun.com/2015/11/13/python-generators-coroutines-native-coroutines-and-async-await.html 也称其为“基于生成器的协程”。

这两种基于生成器的协程是同一个概念吗?

如果不是,它们在用途和用法上有什么区别?

谢谢。

请您参考如下方法:

就我而言,async def 是定义协程的正确方法。 yield 和 yield from 在生成器中有其用途,它们也用于实现“futures”,这是处理不同协程上下文之间切换的低级机制。

我做了this diagram几个月前总结了他们之间的关系。但坦率地说,您可以安全地忽略整个业务。事件循环负责处理管理协程执行的所有低级细节,因此使用其中之一,如 asyncio .还有用于其他事件循环的 asyncio 兼容包装器,比如我自己的 glibcoro用于 GLib/GTK。

换句话说,坚持使用 asyncio API,您就可以编写“事件循环不可知”协程!