python - 如何使用检查模块检查可调用对象是否异步? - Python

标签 python python-3.x async-await coroutine callable

我需要一种高效和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/

相关文章:

python - 什么可以使 signal.signal 长时间阻塞?

python - "from keras.utils import to_categorical"中的错误

python-3.x - 子类和父类的比较

javascript - react-native fetch async/await 响应过滤

c# - 仍然对 C# 中与 GetAwaiter 和 GetResult 一起使用的 ConfigureAwait(false) 感到困惑。遇到死锁或方法不返回

node.js - 在 hapi.js 的处理函数中使用 async/await 返回数据

javascript - Django csrf token + Angularjs

python - Solr:最好的记录、易于使用、稳定的 Python API

python - 网站天真地将 IP 作为形式参数 - 我无法追踪吗?

python-3.x - 更新2 : How Do I Stop a Function in a while loop?