我需要一种高效和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__)
)
关于python - 如何使用检查模块检查可调用对象是否异步? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72382098/