How to Use the Python callable() Function

09/14/2021

Contents

In this article, you will learn how to use the Python callable() function.

Python callable() Function

The callable() function in Python is used to check whether an object is callable or not. An object is considered callable if it can be called like a function.

Syntax

The syntax of the callable() function is:

callable(object)
Parameters
object: The object that you want to check if it is callable or not.
Example

Here are some examples of how to use the callable() function:

Check if a function is callable:
def my_func():
    print("Hello world")
    
print(callable(my_func))   # True
Check if a built-in function is callable:
print(callable(print))   # True
Check if a lambda function is callable:
my_lambda = lambda x: x**2
print(callable(my_lambda))   # True
Check if a list is callable:
my_list = [1, 2, 3]
print(callable(my_list))   # False
Check if an instance of a class is callable:
class MyClass:
    def __init__(self):
        pass
    
    def my_method(self):
        print("Hello world")
        
my_instance = MyClass()

print(callable(my_instance))   # False
print(callable(my_instance.my_method))   # True

As you can see, the callable() function returns True if the object is callable and False if it is not callable.

 

Here are some additional things to keep in mind when using the callable() function:

  • The callable() function works for both built-in functions and user-defined functions.
  • In addition to regular functions and lambda functions, certain objects in Python can also be called like a function. For example, instances of classes that implement the __call__ method can be called like a function. The callable() function can be used to check if an object is an instance of a class with a __call__ method.
  • The callable() function does not raise an exception when given an invalid argument. Instead, it simply returns False. This can be useful when writing defensive code to ensure that you are working with a callable object before trying to call it.