如何检测 Python 变量是否是函数? [英] How do I detect whether a Python variable is a function?
问题描述
我有一个变量,x
,我想知道它是否指向一个函数.
我曾希望我能做这样的事情:
<预><代码>>>>isinstance(x, 函数)但这给了我:
回溯(最近一次调用):文件<stdin>",第 1 行,在 ?NameError:未定义名称函数"
我选择它的原因是
<预><代码>>>>类型(x)<输入'函数'>如果这适用于 Python 2.x 或 Python 3.2+,您可以使用 callable()
.它曾经被弃用,但现在不推荐使用,因此您可以再次使用它.您可以在此处阅读讨论:http://bugs.python.org/issue10518.你可以这样做:
callable(obj)
如果这是针对 Python 3.x 但在 3.2 之前的版本,请检查对象是否具有 __call__
属性.你可以这样做:
hasattr(obj, '__call__')
经常建议的 types.FunctionTypes
或 inspect.isfunction
方法(两者都做完全相同的事情) 附带一些注意事项.它为非 Python 函数返回 False
.例如,大多数内置函数是用 C 而不是 Python 实现的,因此它们返回 False
:
所以 types.FunctionType
可能会给你意想不到的结果.检查鸭子类型对象属性的正确方法是问它们是否嘎嘎叫,而不是看它们是否适合鸭子大小的容器.
I have a variable, x
, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
>>> isinstance(x, function)
But that gives me:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
The reason I picked that is because
>>> type(x)
<type 'function'>
If this is for Python 2.x or for Python 3.2+, you can use callable()
. It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: http://bugs.python.org/issue10518. You can do this with:
callable(obj)
If this is for Python 3.x but before 3.2, check if the object has a __call__
attribute. You can do this with:
hasattr(obj, '__call__')
The oft-suggested types.FunctionTypes
or inspect.isfunction
approach (both do the exact same thing) comes with a number of caveats. It returns False
for non-Python functions. Most builtin functions, for example, are implemented in C and not Python, so they return False
:
>>> isinstance(open, types.FunctionType)
False
>>> callable(open)
True
so types.FunctionType
might give you surprising results. The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container.
这篇关于如何检测 Python 变量是否是函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!