编程语言
首页 > 编程语言> > python – @ types.coroutine和@asyncio.coroutine装饰器有什么区别?

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

作者:互联网

文件说:

@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和更高版本的异步定义具有某些功能).

当需要使用aslcio.coroutine时需要使用types.coroutine,什么是差异?

解决方法:

不同之处在于您是否有收益率声明.
这是代码:

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的调试信息(我们站在“走下去!”一行).控制台中没有打印任何内容,因此功能尚未启动.

PyCharm Debug

但是如果我们删除了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")


@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())

现在我们在控制台打印的类型中做了一些事情.这是调试信息:

new debug info

你可以看到它在调用后立即启动,如果没有结果并返回None.

至于用法,你应该始终使用asyncio版本.如果你需要像火一样运行它并忘记(立即运行并在以后获得结果) – 使用ensure_future函数.

标签:python-3-5,python,asynchronous
来源: https://codeday.me/bug/20190926/1821483.html