在Python中是否有一种通用的方法来检查对象是否是任何函数类型?
题
我在 Python 中有一个函数,它迭代从 dir(obj) 返回的属性,我想检查其中包含的任何对象是否是函数、方法、内置函数等。通常你可以使用 callable() 来实现这一点,但我不想包含类。到目前为止我想出的最好的办法是:
isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType))
有没有一种更面向未来的方法来进行这项检查?
编辑: 我之前说错话了:“通常,您可以使用Callable()为此,但我不想取消课程的资格。”其实我 做 想要取消班级资格。我要匹配 仅有的 函数,而不是类。
解决方案
检查模块正是您想要的:
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))
其他提示
如果您想排除类和其他可能具有 __call__
方法,并且只检查函数和方法,这三个函数在 inspect
模块
inspect.isfunction(obj)
inspect.isbuiltin(obj)
inspect.ismethod(obj)
应该以面向未来的方式做你想做的事。
if hasattr(obj, '__call__'): pass
这也更符合 Python 的“鸭子类型”哲学,因为你并不真正关心 什么 是的,只要你能调用它。
值得注意的是 callable()
正在从 Python 中删除,并且在 3.0 中不再存在。
取决于你所说的“类”的含义:
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
不隶属于 StackOverflow