89DEVs

Python callable() function

The callable() function is used to test if the object appears callable. It is important to understand, that if an object appears callable it might actually not be callable.

callable() on functions

In this example we check if the test() function appears callable. def test(): pass print(callable(test)) The function test() is a callable function and therefore appears callable, True is returned: True

callable() on classes

The callable() function is also useful for checking classes. class Test: def __call__(self): print('test') print(callable(Test)) The class Test is callable and therefore is considered callable by the callable() function, True is returned: True

Class appears callable but isn't

In this example the class Test appears callable, and the callable() function returns True. However it is actually not callable. class Test: def printLine(self): print('print test') print(callable(Test)) The class Test appears callable to the callable() function: True To see if the class is actually callable we run: InstanceOfTest = Test() InstanceOfTest() The code will raise an TypeError because the object is not callable. TypeError: 'Test' object is not callable

callable() syntax

The syntax of the callable() function is: callable(object)

callable() arguments

The callable() function takes exactly one argument. If less or more arguments are given, a TypeError exception is raised.

callable() return values

The callable() function returns True, if the object appears callable. It returns False, if the object is not callable. However like demonstrated above, it is possible that an object appears callable, but isn't callable. If the object appears not callable, then it's definitely not callable.

                
        

Summary


Click to jump to section