Home >Backend Development >Python Tutorial >How to Check if a Variable Refers to a Function in Python?

How to Check if a Variable Refers to a Function in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 20:04:03595browse

How to Check if a Variable Refers to a Function in Python?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn