In Python, callable() is a built-in function used to check whether an object can be called like a function. It returns True when the object appears callable and False otherwise.
def greet():
print("Hello")
print(callable(greet))
print(callable(10))
Output
True False
Explanation:
- greet function is passed to callable() without calling it, so Python checks whether the function object can be invoked.
- callable(greet) returns True.
- Integer 10 cannot be called like a function and returns False.
Syntax
callable(object)
It takes only one argument, an object, and returns one of the two values:
- returns True, if the object appears to be callable.
- returns False, if the object is not callable.
Different Scenario
There may be few cases where callable() may return True even though calling the object later can still fail, for example when incorrect arguments are supplied.
When Object is Callable
Example 1:
def Geek():
return 5
let = Geek
print(callable(let))
num = 5 * 5
print(callable(num))
Output
True
False
Example:
- Geek is assigned to let without parentheses, so let refer to the function itself rather than its returned value.
- Function can be invoked, callable(let) returns True.
- Whereas num stores the integer result of an arithmetic operation and is not callable.
Example 2:
class Geek:
def __call__(self):
print('Hello GeeksforGeeks')
GeekObject = Geek()
print(callable(GeekObject))
GeekObject()
Output
True Hello GeeksforGeeks
Explanation:
- Geek class defines call(0, which allows instances to be invoked using parentheses like a function.
- Therefore, GeekObject is callable, and calling it executes call() and prints the messages.
When Object is NOT callable
Example:
class Geek:
def testFunc(self):
print('Hello GeeksforGeeks')
print(callable(Geek))
GeekObject = Geek()
GeekObject()
Output:
True
Traceback (most recent call last):
File "/home/3979dc83032f2d29befe45b6ee6001a4.py", line 10, in
GeekObject()
TypeError: 'Geek' object is not callable
Explanation:
- Geek class itself is callable because classes can be called to create objects, so callable(Geek) returns True.
- GeekObject does not define call(), so attempting to execute GeekObject() raises a TypeError.