有没有一种通用的方法可以在Python中检查对象是否为函数类型?

时间:2020-03-05 18:56:26  来源:igfitidea点击:

我在Python中有一个函数,该函数正在遍历从dir(obj)返回的属性,并且我想检查其中包含的任何对象是否是函数,方法,内置函数等。通常可以使用为此,可以调用(),但我不想包含类。到目前为止,我想出的最好的方法是:

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

有没有更适合未来的方法来进行此检查?

编辑:我之前说过:"通常我们可以为此使用callable(),但我不想取消类的资格。"我实际上确实想取消课程资格。我只想匹配函数,而不是类。

解决方案

回答

if hasattr(obj, '__call__'): pass

这也更适合Python的"鸭子输入"哲学,因为只要我们可以调用它,我们就并不在乎它是什么。

值得注意的是,callable()已从Python中删除,并且在3.0中不存在。

回答

如果要排除可能具有__call__方法的类和其他随机对象,而仅检查函数和方法,则可以在inspect模块中使用这三个函数

inspect.isfunction(obj)
inspect.isbuiltin(obj)
inspect.ismethod(obj)

应该以适应未来发展的方式来做我们想做的事情。

回答

根据我们对"班级"的含义:

callable( obj ) and not inspect.isclass( obj )

或者:

callable( obj ) and not isinstance( obj, types.ClassType )

例如," dict"的结果是不同的:

>>> callable( dict ) and not inspect.isclass( dict )
False
>>> callable( dict ) and not isinstance( dict, types.ClassType )
True

回答

检查模块正是我们想要的:

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