文件上说:
@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
时,有什么区别?在
另一个细微的区别是:用
@asyncio.coroutine
修饰的基于生成器的协同程序将测试True
是否为asyncio.iscoroutinefunction()
,而那些用@types.coroutine
修饰的协程将测试False
。在输出:
^{pr2}$尽管如此,这两个都是值得期待的。在
*还请注意,这种差异并不适用于它们的结果:将}+
iscoroutinefunction()
替换为iscoroutine()
(它测试协同程序对象),并且{old_coro_with_types()
将两者的结果都为False。区别在于你是否有收益率声明。 代码如下:
在这个例子中,一切看起来都是一样的——这是来自pycharm的调试信息(我们站在“Going down!”线路)。控制台中尚未打印任何内容,因此函数尚未启动。在
但是如果我们删除
^{pr2}$yield
,那么types
版本将立即开始工作!在现在我们在控制台中打印了
doing something in types
。下面是调试信息:正如您所看到的如果没有结果并且返回None,它将在调用之后立即开始。在
至于用法,您应该始终使用
asyncio
版本。如果您需要像fire and forget一样运行它(立即运行,稍后获得结果)-请使用ensure_future
函数。在相关问题 更多 >
编程相关推荐