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__ 方法的用法分析

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...