测试函数或方法是正常还是异步 [英] Test if function or method is normal or asynchronous

查看:78
本文介绍了测试函数或方法是正常还是异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I find out if a function or method is a normal function or an async function? I would like my code to automatically support normal or async callbacks and need a way to test what type of function is passed.

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().

And depending on what type of function gets passed it should either run it normally or with await. I tried various things but have no idea how to implement isAsync().

推荐答案

使用 inspect Python模块.

Use the inspect module of Python.

inspect.iscoroutinefunction(object)

如果对象是协程函数(使用异步def语法定义的函数),则返回true.

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

此功能自Python 3.5开始可用. 该模块适用于功能较少的Python 2,并且肯定没有您需要的功能: inspect

This function is available since Python 3.5. The module is available for Python 2 with lesser functionalities and certainly without the one you are looking for: inspect

Inspect模块对检查很多东西很有用.文档说

Inspect module as the name suggests is useful to inspect a whole lot of thing. The documentation says

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.

该模块的一些基本功能是:

Some basic capabilities of this module are:

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

它还具有检索源代码的功能

It also packs capability to retrieve the source code

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

方法直观地命名.如有需要,可以在文档中找到说明.

Methods are named intuitively. Description if needed can be found in documentation.

这篇关于测试函数或方法是正常还是异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆