How do I check if a value is a function in Python?
Rashid D
rashid d profile pic

In Python, you can check if a value is a function using thecallable() function or by using thetypes module. Here's a detailed explanation of each approach: Using the callable() function: Thecallable() function in Python allows you to check if an object is callable, i.e., if it can be called as a function. This includes checking if a value is a built-in function, a user-defined function, a lambda function, or an instance of a class that implements the__call__() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

def my_function():
    pass

class MyClass:
    def __call__(self):
   pass

# Check if a value is a function
print(callable(my_function))  # Output: True

# Check if an instance of a class is a function
my_instance = MyClass()
print(callable(my_instance))  # Output: True

# Check if an integer is a function
print(callable(10))  # Output: False

In this example,callable(my_function) returnsTrue becausemy_function is a user-defined function. Similarly,callable(my_instance) returnsTrue becausemy_instance is an instance of theMyClass class, which implements the__call__() method. However,callable(10) returnsFalse because integers are not callable objects. Using the types module: Another approach is to use thetypes module, which provides functions and classes for working with different types and checking type-related information. You can usetypes.FunctionType to check if a value is a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

import types

def my_function():
    pass

class MyClass:
    def __call__(self):
   pass

# Check if a value is a function
print(isinstance(my_function, types.FunctionType))  # Output: True

# Check if an instance of a class is a function
my_instance = MyClass()
print(isinstance(my_instance, types.FunctionType))  # Output: False

# Check if an integer is a function
print(isinstance(10, types.FunctionType))  # Output: False

In this example,isinstance(my_function, types.FunctionType) returnsTrue becausemy_function is a function. However,isinstance(my_instance, types.FunctionType) returnsFalse becausemy_instance is an instance of theMyClass class, not a function. Similarly,isinstance(10, types.FunctionType) returnsFalse because integers are not functions. Summary: To check if a value is a function in Python, you can use thecallable() function or thetypes module. Thecallable() function allows you to determine if an object is callable, including functions and objects that implement the__call__() method. Thetypes.FunctionType class from thetypes module allows you to directly check if a value is a function. Understanding how to check if a value is a function helps you perform dynamic type checking and handle different object types effectively within your Python programs. Choose the method that best suits your needs based on the specific requirements and context of your code.