我有一个变量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'>
当前回答
从Python 2.1开始,你可以从inspect模块导入isfunction。
>>> from inspect import isfunction
>>> def f(): pass
>>> isfunction(f)
True
>>> isfunction(lambda x: x)
True
其他回答
Python的2to3工具(http://docs.python.org/dev/library/2to3.html)建议:
import collections
isinstance(obj, collections.Callable)
这似乎是选择了hasattr(x, '__call__')方法,因为http://bugs.python.org/issue7006。
注意,Python类也是可调用的。
要获得函数(这里的函数指的是标准函数和lambdas),请使用:
import types
def is_func(obj):
return isinstance(obj, (types.FunctionType, types.LambdaType))
def f(x):
return x
assert is_func(f)
assert is_func(lambda x: x)
一个精确的功能检查器
Callable是一个很好的解决方案。然而,我想用与John Feminella相反的方式来对待这个问题。不要像这样对待它:
检查鸭子类型对象属性的正确方法是询问它们是否嘎嘎叫,而不是查看它们是否适合鸭子大小的容器。“直接比较”的方法会对许多函数给出错误的答案,比如内置函数。
我们会这样对待它:
判断一个东西是不是鸭子的正确方法不是看它会不会嘎嘎叫,而是通过几个过滤器来判断它是否真的是一只鸭子,而不是仅仅从表面上看它是否像一只鸭子。
我们将如何实现它
'types'模块有很多类来检测函数,最有用的是类型。FunctionType,但也有很多其他类型,比如方法类型、内置类型和lambda类型。我们还将考虑一个'functools '。作为函数的Partial对象。
检查它是否是函数的简单方法是对所有这些类型使用isinstance条件。以前,我想创建一个继承上述所有类的基类,但我无法做到这一点,因为Python不允许我们继承上面的一些类。
下面是一个表,说明什么类可以分类什么函数:
以上函数表由kinght-金编写
实现它的代码
现在,这段代码完成了我们上面描述的所有工作。
from types import BuiltinFunctionType, BuiltinMethodType, FunctionType, MethodType, LambdaType
from functools import partial
def is_function(obj):
return isinstance(obj, (BuiltinFunctionType, BuiltinMethodType, FunctionType, MethodType, LambdaType, partial))
#-------------------------------------------------
def my_func():
pass
def add_both(x, y):
return x + y
class a:
def b(self):
pass
check = [
is_function(lambda x: x + x),
is_function(my_func),
is_function(a.b),
is_function(partial),
is_function(partial(add_both, 2))
]
print(check)
>>> [True, True, True, False, True]
一个false是is_function(partial),因为那是一个类,而不是一个函数,而这正是函数,而不是类。下面是一个预览,您可以从中试用代码。
结论
Callable (obj)是检查对象是否是函数的首选方法,如果您想通过鸭子类型检查绝对值。
我们的自定义is_function(obj),如果你没有将任何可调用的类实例作为函数,而只是内置或lambda, def或partial定义的函数,那么可能经过一些编辑后,它是检查对象是否是函数的首选方法。
我想这就是全部内容了。祝你有愉快的一天!
这里有一些其他的方法:
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!
如果你学过c++,你一定熟悉函数对象或函子,这意味着任何可以像函数一样调用的对象。
在c++中,普通函数是函数对象,函数指针也是;更一般地说,定义operator()的类的对象也是。在c++ 11及以上版本中,lambda表达式也是函子。
相似的是,在Python中,这些函子都是可调用的。一个普通的函数可以被调用,一个lambda表达式可以被调用,一个函数。Partial可以被调用,具有__call__()方法的类的实例可以被调用。
好,回到问题:我有一个变量x,我想知道它是否指向一个函数。
如果你想判断对象是否像一个函数,那么@John Feminella建议的callable方法是可以的。 如果您想判断一个对象是否只是一个普通函数(不是一个可调用的类实例或lambda表达式),那么xtypes。@Ryan建议的XXX是更好的选择。
然后我用这些代码做了一个实验:
#!/usr/bin/python3
# 2017.12.10 14:25:01 CST
# 2017.12.10 15:54:19 CST
import functools
import types
import pprint
定义一个类和一个普通函数。
class A():
def __call__(self, a,b):
print(a,b)
def func1(self, a, b):
print("[classfunction]:", a, b)
@classmethod
def func2(cls, a,b):
print("[classmethod]:", a, b)
@staticmethod
def func3(a,b):
print("[staticmethod]:", a, b)
def func(a,b):
print("[function]", a,b)
定义函子:
#(1.1) built-in function
builtins_func = open
#(1.2) ordinary function
ordinary_func = func
#(1.3) lambda expression
lambda_func = lambda a : func(a,4)
#(1.4) functools.partial
partial_func = functools.partial(func, b=4)
#(2.1) callable class instance
class_callable_instance = A()
#(2.2) ordinary class function
class_ordinary_func = A.func1
#(2.3) bound class method
class_bound_method = A.func2
#(2.4) static class method
class_static_func = A.func3
定义函子列表和类型列表:
## list of functors
xfuncs = [builtins_func, ordinary_func, lambda_func, partial_func, class_callable_instance, class_ordinary_func, class_bound_method, class_static_func]
## list of type
xtypes = [types.BuiltinFunctionType, types.FunctionType, types.MethodType, types.LambdaType, functools.partial]
判断函数是否可调用。如您所见,它们都是可调用的。
res = [callable(xfunc) for xfunc in xfuncs]
print("functors callable:")
print(res)
"""
functors callable:
[True, True, True, True, True, True, True, True]
"""
判断函数类型(types.XXX)。那么函子的类型就不一样了。
res = [[isinstance(xfunc, xtype) for xtype in xtypes] for xfunc in xfuncs]
## output the result
print("functors' types")
for (row, xfunc) in zip(res, xfuncs):
print(row, xfunc)
"""
functors' types
[True, False, False, False, False] <built-in function open>
[False, True, False, True, False] <function func at 0x7f1b5203e048>
[False, True, False, True, False] <function <lambda> at 0x7f1b5081fd08>
[False, False, False, False, True] functools.partial(<function func at 0x7f1b5203e048>, b=4)
[False, False, False, False, False] <__main__.A object at 0x7f1b50870cc0>
[False, True, False, True, False] <function A.func1 at 0x7f1b5081fb70>
[False, False, True, False, False] <bound method A.func2 of <class '__main__.A'>>
[False, True, False, True, False] <function A.func3 at 0x7f1b5081fc80>
"""
我用这些数据绘制了一个可调用函子类型的表。
然后你可以选择合适的函子类型。
如:
def func(a,b):
print("[function]", a,b)
>>> callable(func)
True
>>> isinstance(func, types.FunctionType)
True
>>> isinstance(func, (types.BuiltinFunctionType, types.FunctionType, functools.partial))
True
>>>
>>> isinstance(func, (types.MethodType, functools.partial))
False