How to detect whether a Python variable is a function?
Published on Aug. 22, 2023, 12:15 p.m.
To detect whether a Python variable is a function, you can use the callable()
built-in function or the isfunction()
function from the inspect
module. Here are examples of how to use both methods:
Using callable()
:
def my_func():
print("Hello, World!")
a = "foo"
b = my_func
print(callable(a)) # returns False
print(callable(b)) # returns True
In this example, we define a function called my_func()
and create two variables a
and b
. We then use the callable()
function to check if a
and b
are callable objects, i.e., functions that can be called using parentheses. The function returns False
for the string variable a
and True
for the function object b
.
Using isfunction()
:
import inspect
def my_func():
print("Hello, World!")
a = "foo"
b = my_func
print(inspect.isfunction(a)) # returns False
print(inspect.isfunction(b)) # returns True
In this example, we use the isfunction()
method from the inspect
module to check whether a
and b
are functions. The function returns False
for the string variable a
and True
for the function object b
.
Note that both methods are based on the same concept that functions are callable objects in Python.