为什么不将一个函数声明为type.CoroutineType类型的异步函数? [英] Why isn't a function declared as async of type types.CoroutineType?
问题描述
从此处引用:
types.CoroutineType
协程对象的类型,由异步def函数创建.
The type of coroutine objects, created by async def functions.
此处的引用:
使用async def语法定义的函数始终是协程函数,即使它们不包含await或async关键字.
Functions defined with async def syntax are always coroutine functions, even if they do not contain await or async keywords.
Python控制台会话:
Python console session:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import types
>>> def f(): pass
...
>>> async def g(): pass
...
>>> isinstance(f, types.FunctionType)
True
>>> isinstance(g, types.FunctionType)
True
>>> isinstance(g, types.CoroutineType)
False
>>>
为什么isinstance(g, types.CoroutineType)
不评估为True
?
推荐答案
协程和协程函数之间有区别.生成器和生成器功能之间存在差异的方法相同:
There's a difference between coroutine and coroutine function. The same way as there is a difference between generator and generator function:
调用函数g
会返回一个协程,例如:
Calling the function g
returns a coroutine, e.g.:
>>> isinstance(g(), types.CoroutineType)
True
如果您需要确定g
是否是协程函数(即将返回协程),则可以使用以下方法进行检查:
If you need to tell if g
is a coroutine function (i.e. would return a coroutine) you can check with:
>>> from asyncio import iscoroutinefunction
>>> iscoroutinefunction(g)
True
这篇关于为什么不将一个函数声明为type.CoroutineType类型的异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!