callable() is a built-in method in Python that checks if a passed object appears to be
callable() only takes in a single parameter: the
object to be checked.
The function returns
True if the object appears to be callable. Otherwise, it returns
Note: The function may have false positives. This means the call to the object might fail even if
True. However, if the function returns
False, the call to the object will always fail.
# Object 1 x = 10 def sampleFunction(): print("Hello World!") # Object 2 y = sampleFunction # Checking if Object 1 and Object 2 appear to be callable print("Object 1: ", callable(x)) print("Object 2: ", callable(y)) # Checking if Object 2 is truly callable y()
In the example above, the
callable() function correctly indicates the callability of the two objects.
# creating classes class sampleClass1: def __call__(self): print("This is sample class one!") class sampleClass2: def sampleFunction(): print("This is sample class two!") # creating object 1 x = sampleClass1() print("Object 1: ", callable(x)) x() # checking if sampleClass2 is callable print("sampleClass2: ", callable(sampleClass2)) # creating object 2 y = sampleClass2() y() # This will throw an error
In this example, the instance of the
sampleClass1 class appears to be callable and is actually callable.
On the other hand, the
sampleClass2 class appears to be callable, but the instance of the class is not callable, and an error is thrown.
View all Courses