Skip to main content
 首页 » 编程设计

python之检测使用 async def 创建的任何函数

2024年11月24日7findumars

我对 Python 3.6+ 中的以下行为感到困惑:

>>> def f1(): pass 
>>> def f2(): yield 
>>> async def f3(): pass 
>>> async def f4(): yield 
>>> inspect.isfunction(f1) 
True 
>>> inspect.isfunction(f2) 
True 
>>> inspect.iscoroutinefunction(f3) 
True 
>>> inspect.iscoroutinefunction(f4) 
False 

同步函数和生成器函数都被 inspect 视为“函数”,但异步生成器函数不被视为“协程函数”。 这似乎与documentation相反

inspect.iscoroutinefunction(object)

Return true if the object is a coroutine function (a function defined with an async def syntax).

有没有比检查 iscoroutinefunction 和 isasyncgenfunction 更好的方法来检测函数是否使用 async 定义,包括生成器函数?

这可能是因为异步生成器在 3.6 中才出现,但仍然令人费解。

请您参考如下方法:

异步生成器本身不是协程,不能被 awaited:

>>> 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 

我认为您已经确定了检查 async 是否用于定义函数的最佳方法:

def async_used(func): 
    return inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func)