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

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

>>> isinstance(x, function)

但这给了我:

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

我选这个是因为

>>> type(x)
<type '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): = = ' <内置函数)

其他回答

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

在一些答案中提到的使用hasattr(obj, '__call__')和callable(.)的解决方案有一个主要缺点:对于具有__call__()方法的类和类的实例,它们都返回True。如。

>>> import collections
>>> Test = collections.namedtuple('Test', [])
>>> callable(Test)
True
>>> hasattr(Test, '__call__')
True

检查一个对象是否是用户定义的函数(只有a that)的一个正确方法是使用isfunction(.):

>>> import inspect
>>> inspect.isfunction(Test)
False
>>> def t(): pass
>>> inspect.isfunction(t)
True

如果您需要检查其他类型,请查看inspect -检查活动对象。

在内置命名空间中没有构造函数的内置类型(例如函数、生成器、方法)在types模块中。你可以使用类型。isinstance调用中的函数类型:

>>> import types
>>> types.FunctionType
<class 'function'>

>>> def f(): pass

>>> isinstance(f, types.FunctionType)
True
>>> isinstance(lambda x : None, types.FunctionType)
True

注意,这里使用了一个非常具体的“函数”概念,这通常不是您所需要的。例如,它拒绝zip(严格来说是一个类):

>>> type(zip), isinstance(zip, types.FunctionType)
(<class 'type'>, False)

Open(内置函数有不同类型):

>>> type(open), isinstance(open, types.FunctionType)
(<class 'builtin_function_or_method'>, False)

和随机的。Shuffle(技术上是一种隐藏随机的方法。随机实例):

>>> type(random.shuffle), isinstance(random.shuffle, types.FunctionType)
(<class 'method'>, False)

如果你在做一些特定类型的事情。FunctionType实例,如反编译字节码或检查闭包变量,使用类型。FunctionType,但如果你只是需要一个对象像函数一样可调用,请使用callable。

这里有一些其他的方法:

def isFunction1(f) :
    return type(f) == type(lambda x: x);

def isFunction2(f) :
    return 'function' in str(type(f));

我是这样想到第二个的:

>>> type(lambda x: x);
<type 'function'>
>>> str(type(lambda x: x));
"<type 'function'>"
# Look Maa, function! ... I ACTUALLY told my mom about this!

从Python 2.1开始,你可以从inspect模块导入isfunction。

>>> from inspect import isfunction
>>> def f(): pass
>>> isfunction(f)
True
>>> isfunction(lambda x: x)
True