深度阅读

How to detect whether a Python variable is a function?

作者
作者
2023年08月22日
更新时间
12.32 分钟
阅读时间
0
阅读量

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.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。