callable() Function in Python

Python callable() Function

The callable() function in Python is a built-in function that allows you to check if an object is callable, which means it can be called as a function. It returns True if the object is callable, and False otherwise.

Here's the syntax for the callable() function:

callable(object)

The object parameter represents the object you want to check if it's callable. It can be any Python object, such as a function, method, class, or an instance of a class.

Example:

def say_hello():
    print("Hello!")

class MyClass:
    def my_method(self):
        print("Inside the method")

obj1 = say_hello
obj2 = MyClass()

print(callable(obj1))  # Output: True
print(callable(obj2))  # Output: False

In the example above, say_hello is a function, so callable(obj1) returns True. On the other hand, obj2 is an instance of the MyClass class, and it is not callable, so callable(obj2) returns False.

You can use the callable() function when you need to determine whether an object can be called as a function before actually invoking it, which can be useful for handling dynamic code execution or verifying the capabilities of an object before using it in a specific context.