我有一个变量x,我想知道它是否指向一个函数。

我希望我能做一些像这样的事情:

>>> isinstance(x, function)

但这给了我:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'function' is not defined

我选这个是因为

>>> type(x)
<type 'function'>

当前回答

尝试使用callable(x)。

摘录:

如果对象参数显示为可调用,则返回True,否则返回False。

其他回答

如果你想检测所有语法上看起来像函数的东西:函数、方法、内置的fun/meth、lambda…但排除可调用对象(定义了__call__方法的对象),然后尝试这个:

import types
isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType, types.UnboundMethodType))

我将其与inspect模块中的is*()检查代码进行了比较,上面的表达式要完整得多,特别是如果您的目标是过滤任何函数或检测对象的常规属性。

使用isinstance()和type(),它们都是Python中的内置函数,你可以检查它是否是一个函数,这样你就不需要导入任何东西:

def test():
    pass

print(isinstance(test, type(test)))

输出:

True

你可以试试这个:

if obj.__class__.__name__ in ['function', 'builtin_function_or_method']:
    print('probably a function')

或者更奇怪的事情:

if "function" in lower(obj.__class__.__name__):
    print('probably a function')

在Python3中,我提出了type (f) == type (lambda x:x),如果f是一个函数,则输出True,如果不是则输出False。但我想我更喜欢isinstance (f, types.FunctionType),它感觉不那么特别。我想写type (f) is function,但这行不通。

结合@Sumukh Barve, @Katsu和@tinnick的回答,如果你的动机只是想在控制台中获取可用的内置函数列表,这两个选项是可行的:

(我对j __builtin__.__dict__.items如果j.__class__()。__name__ in ['function', 'builtin_function_or_method']] (我对j __builtin__.__dict__.items()如果str (j)(18): = = ' <内置函数)