callable()
is a built-in method in Python that checks if a passed object appears to be
__call__
method.callable(object)
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 False
.
Note: The function may have false positives. This means the call to the object might fail even if
callable()
returnsTrue
. However, if the function returnsFalse
, the call to the object will always fail.
# Object 1x = 10def sampleFunction():print("Hello World!")# Object 2y = sampleFunction# Checking if Object 1 and Object 2 appear to be callableprint("Object 1: ", callable(x))print("Object 2: ", callable(y))# Checking if Object 2 is truly callabley()
In the example above, the callable()
function correctly indicates the callability of the two objects.
# creating classesclass sampleClass1:def __call__(self):print("This is sample class one!")class sampleClass2:def sampleFunction():print("This is sample class two!")# creating object 1x = sampleClass1()print("Object 1: ", callable(x))x()# checking if sampleClass2 is callableprint("sampleClass2: ", callable(sampleClass2))# creating object 2y = 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.