我有一个变量x,我想知道它是否指向一个函数。
我希望我能做一些像这样的事情:
>>> isinstance(x, function)
但这给了我:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
我选这个是因为
>>> type(x)
<type 'function'>
我有一个变量x,我想知道它是否指向一个函数。
我希望我能做一些像这样的事情:
>>> isinstance(x, function)
但这给了我:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
我选这个是因为
>>> type(x)
<type 'function'>
当前回答
下面是一个“repr方法”来检查它。它也适用于。
def a():pass
type(a) #<class 'function'>
str(type(a))=="<class 'function'>" #True
b = lambda x:x*2
str(type(b))=="<class 'function'>" #True
其他回答
在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 -检查活动对象。
根据之前的回复,我想出了这个:
from pprint import pprint
def print_callables_of(obj):
li = []
for name in dir(obj):
attr = getattr(obj, name)
if hasattr(attr, '__call__'):
li.append(name)
pprint(li)
被接受的答案在当时被认为是正确的。因为它 结果是,没有callable()的替代品,这又回到了Python中 3.2:具体来说,callable()检查对象的tp_call字段 测试。在普通的Python中没有对等的。大多数建议的测试都是 大多数时候是正确的:
>>> class Spam(object):
... def __call__(self):
... return 'OK'
>>> can_o_spam = Spam()
>>> can_o_spam()
'OK'
>>> callable(can_o_spam)
True
>>> hasattr(can_o_spam, '__call__')
True
>>> import collections
>>> isinstance(can_o_spam, collections.Callable)
True
方法中删除__call__来解决这个问题 类。为了让事情更有趣,在实例中添加一个假__call__ !
>>> del Spam.__call__
>>> can_o_spam.__call__ = lambda *args: 'OK?'
注意这个真的是不可调用的:
>>> can_o_spam()
Traceback (most recent call last):
...
TypeError: 'Spam' object is not callable
Callable()返回正确的结果:
>>> callable(can_o_spam)
False
但是hasattr错了:
>>> hasattr(can_o_spam, '__call__')
True
Can_o_spam确实有这个属性;它只是在调用时不使用 实例。
更微妙的是,isinstance()也会出错:
>>> isinstance(can_o_spam, collections.Callable)
True
因为我们之前使用了这个检查,后来删除了方法abc。ABCMeta 缓存结果。可以说这是abc.ABCMeta中的一个bug。也就是说, 没有比这更准确的结果了 结果比使用callable()本身,因为typeobject->tp_call 槽方法不能以任何其他方式访问。
只需使用callable()
使用isinstance()和type(),它们都是Python中的内置函数,你可以检查它是否是一个函数,这样你就不需要导入任何东西:
def test():
pass
print(isinstance(test, type(test)))
输出:
True