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