python - 测试函数或方法是正常还是异步

标签 python python-3.x asynchronous python-3.5 coroutine

如何确定函数或方法是普通函数还是异步函数?我希望我的代码能够自动支持正常或异步回调,并且需要一种方法来测试传递的函数类型。

async def exampleAsyncCb():
    pass

def exampleNomralCb():
    pass

def isAsync(someFunc):
    #do cool dynamic python stuff on the function
    return True/False

async def callCallback(cb, arg):
    if isAsync(cb):
        await cb(arg)
    else:
        cb(arg)

根据传递的函数类型,它应该正常运行还是等待。我尝试了各种方法,但不知道如何实现 isAsync()

最佳答案

使用 inspect Python的模块。

inspect.iscoroutinefunction(object)

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

此函数从 Python 3.5 开始可用。 该模块可用于功能较少的 Python 2,当然没有您正在寻找的模块:inspect

顾名思义,检查模块对于检查很多东西很有用。文档说

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.

There are four main kinds of services provided by this module: type checking, getting source code, inspecting classes and functions, and examining the interpreter stack.

这个模块的一些基本功能是:

inspect.ismodule(object)
inspect.isclass(object)
inspect.ismethod(object)
inspect.isfunction(object)

它还包含检索源代码的功能

inspect.getdoc(object)
inspect.getcomments(object)
inspect.getfile(object) 
inspect.getmodule(object)

方法的命名很直观。如果需要,可以在文档中找到描述。

关于python - 测试函数或方法是正常还是异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36076619/

相关文章:

python - AWS IoT Python SDK 和 asyncio

python - 在 Python 库中注册机器人框架监听器

python - 如何只获取MySQL表中的字段?

python - 使用 python shelf 类给出编码错误

python - Unicode解码错误: 'ascii' codec can't decode byte 0xe4

python - gevent 到 Tornado ioloop - 带有协程/生成器的结构代码

python - 如何平均分割水平布局或指定尺寸

python - pandas 函数根据匹配列填充其他数据框中的缺失值?

c++ - 是否保证为返回 void 的函数调用 std::async?

angular - 如何等待异步订阅完全填充全局变量?