如果对象是任何函数类型,是否有一种通用的方法来检查 Python? [英] Is there a common way to check in Python if an object is any function type?

查看:28
本文介绍了如果对象是任何函数类型,是否有一种通用的方法来检查 Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中有一个函数,它迭代从 dir(obj) 返回的属性,我想检查其中包含的任何对象是否是函数、方法、构建的-in 函数等.通常您可以为此使用 callable(),但我不想包含类.到目前为止我想出的最好的是:

I have a function in Python which is iterating over the attributes returned from dir(obj), and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use callable() for this, but I don't want to include classes. The best I've come up with so far is:

isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType))

是否有更面向未来的方法来进行此检查?

Is there a more future-proof way to do this check?

我之前说错了:通常你可以使用 callable() 来做这个,但我不想取消课程资格."我实际上确实想要取消课程资格.我想匹配函数,而不是类.

I misspoke before when I said: "Normally you could use callable() for this, but I don't want to disqualify classes." I actually do want to disqualify classes. I want to match only functions, not classes.

推荐答案

inspect 模块有你想要的:

The inspect module has exactly what you want:

inspect.isroutine( obj )

仅供参考,代码是:

def isroutine(object):
    """Return true if the object is any kind of function or method."""
    return (isbuiltin(object)
            or isfunction(object)
            or ismethod(object)
            or ismethoddescriptor(object))

这篇关于如果对象是任何函数类型,是否有一种通用的方法来检查 Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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