Python Built-in Function callable():
The callable() is a built-in function in Python that determines if the object being passed is callable or not. However, this method returns True only if the object is callable, False otherwise. Moreover, if we try to call an object that is not callable, it results in a TypeError Exception.
Method signature
The signature for the callable() method is as shown below. Here, “obj” can be any object of type function, string, list, etc. Also, the variable r
will store a boolean value returned by the callable.
r=callable(obj)
Method parameters and return type
- Here, The callable() method takes an object as a parameter.
- However, it returns the boolean value True or False.
Python Built-in Function callable Examples:
Example 1: In this example, let us check if the user-defined function func is callable or not. Here, we will check for variable num to be callable or not. As we can see, that this method returns false because num is not callable.
#Defining a Function
def func():
print("Python")
# Using callable and printing
r=callable(func)
print("Is function callable? ",r)
num=10
r=callable(num)
print("Is num callable? ",r)
Output
Is function callable? True
Is num callable? False
Example 2: The following example checks built-in objects to see if they are callable or not. Here, we are calling with the object of list, tuple, string and dictionary. Just because, all this objects are callable, this will return True.
#Using callable method and printing
print("Is string class callable?", callable(str))
print("Is list class callable?", callable(list))
print("Is tuple class callable?",callable(tuple))
print("Is dict class callable?",callable(dict))
Output
Is string class callable? True
Is list class callable? True
Is tuple class callable? True
Is dict class callable? True
Example 3: In this example, let us create a class employee and method welcome inside a class. Here, we will check whether the class instance is callable or not. As we can see, the class instance is not callable it raises a TypeError
exception. To make class callable, we have to override the __call__
method of an employee class.
#Defining class
class employee:
def welcome(self):
print("Python")
#Creating instance of a class
e = employee()
#Checking for a callable or not
print("Is employee instance callable? ", callable(e))
# Calling with the instance
print(e())
Output
Is employee instance callable? False
Traceback (most recent call last):
File "main.py", line 9, in
print(e())
TypeError: 'employee' object is not callable
Conclusion
The callable() method returns a true value if the object is callable. However, if the object is not callable this method returns false.
References
Happy Learning 🙂