练习写作coroutines
在Python 3.6中,
注意到两者都在:
from asyncio import coroutine
并且在:
from types import coroutine
有 2 个装饰器,乍一看它们的作用是一样的..
阅读第一个文档(来自 asyncio
)
Decorator to mark coroutine
第二个(来自 types
):
Convert regular generator function to coroutine.
让我更困惑了..
我知道我可以使用 async yield from
在python3.6中,所以我迷失了真正理解两者之间的区别。
请帮忙
最佳答案
随着 async def
的出现语法,这两个装饰器都很少使用,并且 asyncio.coroutine
正式deprecated .
types.coroutine
装饰器作为从生成器创建协程的低级工具仍然很有用。在为自定义事件循环实现制作原语时,这种事情很有用。与@types.coroutine
您可以从准系统生成器创建一个协程,其 yield
直接向事件循环生成您选择的值。
例如,sleep
协程实现可能如下所示:
@types.coroutine
def sleep(delay):
deadline = time.time() + delay
yield 'sleep_until', deadline
这将创建一个与使用async def
创建的协程类似的协程。 ,但具有与兼容事件循环通信的神奇能力,其中可能包含如下代码:
def run(self):
while self._to_run:
coro = self._to_run.popleft()
try:
cmd, arg = coro.send(None)
except StopIteration:
continue
if cmd == 'sleep_until':
self._to_wake[arg] = coro
time.sleep(min(self._to_wake) - time.time())
self._to_run.extend(coro for t, coro in self._to_wake.items()
if t <= time.time())
有关更多详细信息,请参阅this lecture由 David Beazley 制作,在现场观众面前构建了一个功能齐全的事件循环。 (不要因 yield from
的使用而推迟 - 较新的 async def
的工作方式完全相同。)
关于python-3.x - asyncio.coroutine 和 types.coroutine 装饰器有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54096520/