Ham*_*ite 3 python python-3.x async-await
从这里引用:
types.CoroutineType由 async def 函数创建的协程对象的类型。
从这里引用:
使用 async def 语法定义的函数始终是协程函数,即使它们不包含 await 或 async 关键字。
Python控制台会话:
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
>>>
Run Code Online (Sandbox Code Playgroud)
为什么不isinstance(g, types.CoroutineType)评估为True?
协程和协程函数之间是有区别的。与generator和generator function的区别一样:
调用该函数g返回一个协程,例如:
>>> isinstance(g(), types.CoroutineType)
True
Run Code Online (Sandbox Code Playgroud)
如果您需要判断是否g是协程函数(即会返回协程),您可以检查:
>>> from asyncio import iscoroutinefunction
>>> iscoroutinefunction(g)
True
Run Code Online (Sandbox Code Playgroud)