python - @types.coroutine 和 @asyncio.coroutine 装饰器有什么区别?

标签 python asynchronous python-3.5

文档说:

@asyncio.coroutine

Decorator to mark generator-based coroutines. This enables the generator use yield from to call async def coroutines, and also enables the generator to be called by async def coroutines, for instance using an await expression.

_

@types.coroutine(gen_func)

This function transforms a generator function into a coroutine function which returns a generator-based coroutine. The generator-based coroutine is still a generator iterator, but is also considered to be a coroutine object and is awaitable. However, it may not necessarily implement the __await__() method.

所以看起来目的是一样的——将生成器标记为协程(Python3.5 及更高版本中的 async def 对某些功能做了什么)。

什么时候需要使用asyncio.coroutine 什么时候需要使用types.coroutine,有什么区别?

最佳答案

不同之处在于您是否有 yield 语句。 代码如下:

from types import coroutine as t_coroutine
from asyncio import coroutine as a_coroutine, ensure_future, sleep, get_event_loop


@a_coroutine
def a_sleep():
    print("doing something in async")
    yield 1


@t_coroutine
def t_sleep():
    print("doing something in types")
    yield 1


async def start():
    sleep_a = a_sleep()
    sleep_t = t_sleep()
    print("Going down!")


loop = get_event_loop()
loop.run_until_complete(start())

在这个例子中,一切看起来都一样——这是来自 pycharm 的调试信息(我们站在“Going down!”行)。控制台中尚未打印任何内容,因此功能尚未启动。

PyCharm Debug

但是如果我们去掉yieldtypes 版本会立即启动!

from types import coroutine as t_coroutine
from asyncio import coroutine as a_coroutine, ensure_future, sleep, get_event_loop


@a_coroutine
def a_sleep():
    print("doing something in async")


@t_coroutine
def t_sleep():
    print("doing something in types")


async def start():
    sleep_a = a_sleep()
    sleep_t = t_sleep()
    print("Going down!")


loop = get_event_loop()
loop.run_until_complete(start())

现在我们在控制台打印了 doing things in types。这是调试信息:

new debug info

如您所见调用后立即开始,如果没有结果并返回 None。


至于使用,您应该始终使用 asyncio 版本。如果您需要像 fire and forget 一样运行它(立即运行并稍后获得结果) - 使用 ensure_future 函数。

关于python - @types.coroutine 和 @asyncio.coroutine 装饰器有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39637675/

相关文章:

wpf - F# 异步和 WPF 进度条

python - 如何禁用 Jupyter 笔记本 session 的密码请求?

python - 运行 Python 3.5 解释器需要哪些标准库模块?

python - 连接缩进、换行的段落的最 Pythonic 方式?

python - Flask wtform RadioField 标签不呈现

Python 计算唯一列表排列可能性

C# Tcp 通信线程池与异步调用

c# - 与无限循环异步

Python3 Selenium在弹出对话框中填写用户名和密码

python - 张量板显示语法错误 : can't assign to operator