callable() Function in Python

In this tutorial, we will focus on callable() function in Python. We will also check how callable() function works in Python.

A function performs a specific task.

Certainly, anything which can be called, if given to the callable() function will return True.

Certainly, the callable function has two features,

  • Returns True if the argument passed is callable.
  • Moreover, if the argument is not callable, it returns False.

Let’s implement the above function:

def fun ():
    print ("Hello CodeSpeedy")

result = callable(fun)               # fun object passed to callable function 

print (result)
Output :


Certainly, from the code, it is clear that the fun object passed to the callable() function can be called.

Moreover, it’s also good to see what happens if a list object is passed to that function.

l = [ 1, 2, 3]

result = callable(l)               # list object passed to callable function 

print (result)
Output :


From the above two examples, it is very well proven that only function objects are callable.

It seems easy, wait but there is a surprise, nothing but a magic method __call__().

The key point is to note that it is the same as  __init__() which is a class constructor.

Certainly, the example gives more idea about it.

class Dog:
    def __init__(self,price):
        self.price = price
class Cat:
    def __call__(self,price):
        self.price = price

d = Dog (200)          # with __init__ method , __init__ gets invoked

c = Cat ()             # with __call__ method     

c(300)                 # __call__ gets invoked

print ("Price of dog is",d.price)

print ("Price of cat is",c.price)
Output :

Price of dog is 200
Price of cat is 300

Concluding, the callable() function is not used frequently but good to know that it exists in the deep sea of Python.

Leave a Reply

Your email address will not be published. Required fields are marked *