gpt4 book ai didi

python - 为什么不将函数声明为 types.CoroutineType 的异步函数?

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:05 27 4
gpt4 key购买 nike

引自 here :

types.CoroutineType

The type of coroutine objects, created by async def functions.

引自 here :

Functions defined with async def syntax are always coroutine functions, even if they do not contain await or async keywords.

Python 控制台 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

最佳答案

协程和协程函数是有区别的。同理生成器和生成器函数的区别:

调用函数g返回一个协程,例如:

>>> isinstance(g(), types.CoroutineType)
True

如果您需要判断 g 是否是协程函数(即返回协程),您可以检查:

>>> from asyncio import iscoroutinefunction
>>> iscoroutinefunction(g)
True

关于python - 为什么不将函数声明为 types.CoroutineType 的异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34840751/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com