Python 检测使用async def创建的任何函数
我对Python 3.6+中的以下行为感到困惑:Python 检测使用async def创建的任何函数,python,python-3.6,python-asyncio,python-3.7,coroutine,Python,Python 3.6,Python Asyncio,Python 3.7,Coroutine,我对Python 3.6+中的以下行为感到困惑: >>def f1():通过 >>>def f2():屈服 >>>异步def f3():传递 >>>异步def f4():屈服 >>>检查ISF功能(f1) 真的 >>>检查ISF功能(f2) 真的 >>>检查.iscoroutinefunction(f3) 真的 >>>inspect.iscoroutineffunction(f4) 假的 同步功能和发电机功能均被inspect视为“功能”,但异步发电机功能不被视为“协程功能”。 这似乎与实际情
>>def f1():通过
>>>def f2():屈服
>>>异步def f3():传递
>>>异步def f4():屈服
>>>检查ISF功能(f1)
真的
>>>检查ISF功能(f2)
真的
>>>检查.iscoroutinefunction(f3)
真的
>>>inspect.iscoroutineffunction(f4)
假的
同步功能和发电机功能均被inspect视为“功能”,但异步发电机功能不被视为“协程功能”。
这似乎与实际情况相反
inspect.iscoroutinefunction(对象)
如果对象是协程函数(使用异步定义语法定义的函数),则返回true
有没有比同时检查iscoroutinefunction
和isasyncgenfunction
更好的方法来检测函数是否是用async
定义的,包括生成器函数
这可能是因为异步发电机仅出现在3.6中,但仍然令人费解。异步发电机本身并不是协程,不能等待:
>>> loop.run_until_complete(f4())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/haugh/.pyenv/versions/3.6.6/lib/python3.6/asyncio/base_events.py", line 447, in run_until_complete
future = tasks.ensure_future(future, loop=self)
File "/home/haugh/.pyenv/versions/3.6.6/lib/python3.6/asyncio/tasks.py", line 526, in ensure_future
raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
TypeError: An asyncio.Future, a coroutine or an awaitable is required
谢谢,这就解释了为什么
iscoroutineffunction
在f4
上返回False
。我认为在引入异步发电机之后,它的文档应该在3.6中更新。。。
def async_used(func):
return inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func)