如何检查如果一个可调用的对象是异步使用检查模块?——python



我需要一个高效的python检查可调用对象是否异步的方法inspect.iscoroutinefunction无法识别,我已经尝试过了:

import inspect

async def test_func() -> None:
pass

class TestClass:
async def __call__(self) -> None:
pass
test_obj = TestClass()

当测试:

inspect.iscoroutinefunction(test_func)
>>> True
inspect.iscoroutinefunction(test_obj)
>>> False

和测试时:

inspect.iscoroutinefunction(test_func.__call__)
>>> False
inspect.iscoroutinefunction(test_obj.__call__)
>>> True

我可以创建一个这样的辅助函数:

def is_async(func: Callable) -> bool:
try:
return any(map(inspect.iscoroutinefunction, (func, func.__call__)))
except AttributeError:
return False

但我觉得有更简单的方法…

来自starlette:

import asyncio
import functools
import typing

def is_async_callable(obj: typing.Any) -> bool:
while isinstance(obj, functools.partial):
obj = obj.func
return asyncio.iscoroutinefunction(obj) or (
callable(obj) and asyncio.iscoroutinefunction(obj.__call__)
)

最新更新