如何确定函数或方法是普通函数还是异步函数?我希望我的代码自动支持普通或异步回调,并需要一种方法来测试传递的函数类型。
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)
根据传递的函数类型,它应该正常运行或使用await。我尝试了各种方法,但不知道如何实现isAsync()
。
如果不想引入另一个带有
inspect
的导入,也可以在asyncio
中使用iscoroutine
。使用Python的inspect模块。
inspect.iscoroutinefunction(object)
此函数在Python3.5之后可用。 该模块可用于Python 2,但功能较少,而且肯定没有您要寻找的功能:inspect
顾名思义,Inspect模块对于检查很多事情都很有用。文件上说
本模块的一些基本功能包括:
它还打包了检索源代码的功能
方法是直观命名的。如有需要,可在文档中找到说明。
共同例程设置了
COROUTINE
标志,代码标志中的位6:值128作为常量存储在
inspect
模块中:^{} function 就是这样做的;测试对象是否是函数或方法(以确保有一个
__code__
属性)并测试该标志。请参阅source code。当然,使用
inspect.iscoroutinefunction()
是最具可读性的,并且保证在代码标志发生更改时继续工作:相关问题 更多 >
编程相关推荐