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

Detect any function created with async def

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

检查时 "functions" 考虑了同步函数和生成器函数,但不考虑异步生成器函数 "coroutine functions"。 这似乎与documentation

相反

inspect.iscoroutinefunction(object)

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

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

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

异步生成器本身不是协程,不能await编辑:

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