Python callable() Function

Python callable() function is a Python built-in function that returns True if the object is callable, else it returns False.

python callable() function

Python callable()

A callable as the name signifies is anything that can be called. So anything can be called as long as they belong to the class that defines the __call__() magic method.

Python callable() function checks for either of the following.

  • an instance of a class with a __call__() method or
  • is of a type that has a non-null tp_call (c struct) member which indicates callability otherwise (such as in functions, methods etc.)

The method __call__() is invoked when the instance is ”called” as a function.

Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__()method.

Python callable() function returns:

  • True: if the object being called is callable
  • False: if the object being called is not callable

How to check if a Python object is callable or not?

foo = 'Python'
print(callable(foo))  #this will return false

class foo1:
  def __call__(self):
print(callable(foo1))  #this will return true

def foo3():
print(callable(foo3))  #this will return true

#instance of a class
class foo4:
  def test_func(self):
object1 = foo4()
object1()  #this will throw error

This script will generate following output.




Traceback (most recent call last): 
File "<pyshell#3>", line 1, in <module> object1() 
TypeError: 'foo4' object is not callable

As you can see the last line of code where we called the instance of class foo4 raises an error because the instance of class object1 appears as callable but is not in actual.

This is because the object is not associated with any __call__() function in the class foo4.

Now if we define class foo4 with a function __call__(), its instance won’t raise an error and will return True when checked if it’s callable or not.

class foo4:
  def __call__(self):
object1 = foo4()

#check if it's callable or not

Here is the output generated.


As you can see in above output, the object doesn’t raise any error when called and return True when checked.