Python built-in Method - callable()

w‮i.ww‬giftidea.com

The callable() method is a built-in function in Python that returns True if the given object is callable (i.e., can be called like a function) and False otherwise.

Here is the syntax for callable() method:

callable(object)

where object is the object that is being checked for callability.

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

def func():
    pass

class MyClass:
    def method(self):
        pass

my_object = MyClass()

print(callable(func))  # Output: True
print(callable(MyClass))  # Output: True
print(callable(my_object.method))  # Output: True
print(callable(42))  # Output: False

In this example, callable() is used to check whether various objects are callable. The func() function, the MyClass class, and the method() method of my_object are all callable, so callable() returns True for each of them. However, the integer 42 is not callable, so callable() returns False for it.

The callable() method can be useful when working with dynamic code, such as when using higher-order functions that take other functions as arguments. By checking whether a given object is callable before attempting to call it, you can avoid runtime errors and write more robust code.