2017年7月30日 星期日

[ Python 常見問題 ] How to detect whether a python variable is a function?

Source From Here 
Question 
I have a variable, x, and I want to know whether it is pointing to a function or not
>>> def x(a, b):
... return a + b
...
>>> type(x)


How-To 
If this is for Python 2.x or for Python 3.2+, you can also 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(x)
True

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(x, '__call__')
True

The oft-suggested types.FunctionType approach is not correct because it fails to cover many cases that you would presumably want it to pass, like with builtins
>>> import types
>>> isinstance(x, types.FunctionType)
True
>>> isinstance(open, types.FunctionType) // Negative example
False
>>> type(open)

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. Don't use types.FunctionType unless you have a very specific idea of what a function is. 

Supplement 
Python可調用對象 __call__ 方法的用法分析

沒有留言:

張貼留言

[ Py DS ] Ch5 - Machine Learning (Part2)

Source From  Here   Introducing Scikit-Learn   There are several Python libraries that provide solid implementations of a range of machin...