有什么区别@类型.协同程序以及@异步协同程序装修工?

2024-05-15 22:15:21 发布

您现在位置:Python中文网/ 问答频道 /正文

文件上说:

@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时,有什么区别?在


Tags: andthetoasyncioasyncisdeffunction
2条回答

另一个细微的区别是:用@asyncio.coroutine修饰的基于生成器的协同程序将测试True是否为asyncio.iscoroutinefunction(),而那些用@types.coroutine修饰的协程将测试False。在

# testcoro.py
import asyncio
import inspect
import types

@asyncio.coroutine
def old_coro_with_asyncio():
    yield from asyncio.sleep(1)

@types.coroutine
def old_coro_with_types():
    yield from asyncio.sleep(1)

if __name__ == "__main__":
    for coro in (old_coro_with_asyncio, old_coro_with_types):
        print(coro.__name__, 'iscoroutine:', asyncio.iscoroutine(coro))
        print(coro.__name__, 'iscoroutinefunc:', asyncio.iscoroutinefunction(coro))

输出:

^{pr2}$

尽管如此,这两个都是值得期待的。在


*还请注意,这种差异并不适用于它们的结果:将iscoroutinefunction()替换为iscoroutine()(它测试协同程序对象),并且{}+old_coro_with_types()将两者的结果都为False。

区别在于你是否有收益率声明。 代码如下:

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

但是如果我们删除yield,那么types版本将立即开始工作!在

^{pr2}$

现在我们在控制台中打印了doing something in types。下面是调试信息:

new debug info

正如您所看到的如果没有结果并且返回None,它将在调用之后立即开始。在


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

相关问题 更多 >