Detecting Function Variables in Python
You have a variable named "x" and want to determine if it points to a function. While checking the type of "x" shows it's a function, attempting to use isinstance(x, function) fails. This is where callable() comes in handy.
Python 2.x and Python 3.2 :
callable(x)
Python 3.x before 3.2:
hasattr(x, '__call__')
Previous approaches like types.FunctionTypes or inspect.isfunction have limitations. They return False for non-Python functions, such as builtins, which are implemented in C.
Instead of checking the type or fitting into a container, it's best to "ask" the object if it can be called by looking for the call attribute. This ensures accurate identification of functions, regardless of their implementation.
The above is the detailed content of How to Check if a Variable Refers to a Function in Python?. For more information, please follow other related articles on the PHP Chinese website!