Detecting Whether a Variable is a Function
In Python, determining if a variable represents a function can be perplexing. The intuitive approach, isinstance(x, function), fails due to the undefined 'function' reference.
Solution 1: callable()
For Python 2.x or 3.2 , callable() provides a direct and straightforward check:
<code class="python">callable(x)</code>
Solution 2: call Attribute (Python 3.x Before 3.2)
Prior to Python 3.2, one must inspect the object for the __call__ attribute:
<code class="python">hasattr(x, '__call__')</code>
Caveats with Types and Inspection
While types.FunctionTypes and inspect.isfunction methods exist, they may provide unexpected results. Non-Python functions, such as many builtins, return False using these methods:
<code class="python">import types, inspect isinstance(open, types.FunctionType) # False callable(open) # True</code>
Best Practice: Duck Typing
Rather than relying on isinstance or inspect, the preferred approach is to check if the object can be called, mimicking the "duck-typed" principle:
<code class="python">def quacks_like_a_function(x): return callable(x)</code>
The above is the detailed content of How to Detect Whether a Variable Represents a Function in Python?. For more information, please follow other related articles on the PHP Chinese website!