callable() method returns True if the object passed to it appears to be callable, else it returns False. Callable means something that can be called.
The syntax of
callable() method is:
callable() method takes a single parameter object and can return one of the two possible values:
- True if the object appears to be callable
- False if the object doesn't appear to be callable
Note: In some cases,
callable() returns True, but the call to the object can still fail. However, if the
callable() method returns False, the call to the object will definitely fail.
def my_func(): print("I am a function, I can be called!") func = my_func print(callable(func)) my_var = 20 print(callable(my_var))
In the first case, an object
func of the
my_func function is created and passed to the
callable() method which appears to be callable. Hence it returns True. However, in the second case, an object
my_var is passed which is definitely not callable. Hence, it returns False.
The callable() method checks if the argument is either of the following:
- an instance of class with a call method
- of a type that indicates callability such as method or function
class TestClass1: def __call__(self): print("Test Class 1 called") obj1 = TestClass1() print(callable(obj1)) obj1()
True Test Class 1 called
In the above example, the
__call__ method implemented, and hence appears to be callable, and is callable.
class TestClass2: def my_method(self): print("Test Class 2 called") obj2 = TestClass2() print(callable(obj2)) obj2()
False Traceback (most recent call last): File "D:\Quarantine\Test\Blog-Codes\Built-Ins\callable\ex2.py", line 17, in <module> obj2() TypeError: 'TestClass2' object is not callable
However, in the above example, the
TestClass2 appears to be callable, but the instance of the class is not callable, and hence an error is thrown.
In this part, we learned about the Python
callable() function with the help of examples.