2021年6月27日 星期日

[ Python 常見問題 ] How do I 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.

I had hoped I could do something like:
  1. >>> isinstance(x, function)  
But that gives me:
  1. Traceback (most recent call last):  
  2.   File "<stdin>", line 1, in ?  
  3. NameError: name 'function' is not defined  
The reason I picked that is because
  1. >>> type(x)  
  2. <type 'function'>  
HowTo
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:
If this is for Python 3.x but before 3.2, check if the object has a __call__ attribute. You can do this with:
  1. hasattr(obj, '__call__')  
The oft-suggested types.FunctionType or inspect.isfunction approach (both do the exact same thingcomes 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:
  1. >>> isinstance(open, types.FunctionType)  
  2. False  
  3. >>> callable(open)  
  4. True  
so types.FunctionType might give you surprising results. The proper way to check the properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container.

沒有留言:

張貼留言

[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...