ItsMyCode |
The callable()
function in Python returns True
if the object passed appears to be callable. Otherwise, it returns False
.
callable() Syntax
The syntax of the callable()
method is
**callable(object)**
callable() Parameters
The callable()
method can take only one argument, i.e., an object.
callable() Return Value
The callable()
function returns
-
True
– if the object appears callable -
False
– if the object is not callable.
Note: There may be few cases where callable()
returns True , but the call to the object may fail. But in case if callable()
returns False , the calling object will never succeed.
Example 1: How does callable() works?
Here, the object number
is not callable. And, the object getData
appears to be callable (but may not be callable).
# returns false as the object of integer is not callable
number = 10
print(callable(number))
def getData():
print("Hello World")
# returns true as the variable is callable
obj = getData
print(callable(obj))
Output
False
True
Example 2: When an Object is callable
The built-in callable()
method checks if the argument passed is either of the below two cases:
- An instance of a class having a ` __call_ `_ method.
- It is of a type that indicates callability, such as in functions, methods, etc. or has a non-null
tp_call
(c struct) member.
# Python program to demonstrate callable()
class Test:
def __call__ (self):
print('Hello World !!!')
# Suggests that Test class is callable and returns True
print(callable(Test))
# This proves that class is callable
TestObject = Test()
TestObject()
Output
True
Hello World !!!
Example 3: When an Object is NOT callable
The callable()
method returns True , suggesting that the Test class is callable, but the instance of Test ** is not callable, and it returns a **TypeError: ‘Test’ object is not callable
# Python program to demonstrate NOT callable()
class Test:
def printdata(self):
print('Hello World !!!')
# Suggests that Test class is callable and returns True
print(callable(Test))
# The object will be created but returns error while calling
TestObject = Test()
TestObject()
Output
True
Traceback (most recent call last):
File "c:\Projects\Tryouts\main.py", line 11, in <module>
TestObject()
TypeError: 'Test' object is not callable
The post Python callable() appeared first on ItsMyCode.
Top comments (0)