gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:05:06 26 4
gpt4 key购买 nike

文档说:

@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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com