Python callable() Function
The callable()
function returns True
if the specified object is callable, otherwise it returns False
.
Syntax
callable(object)
callable() Parameters
Python callable()
function parameters:
Parameter | Condition | Description |
---|---|---|
object | Required | The object you want to test if it is callable or not. |
callable() Return Value
Python callable()
method returns:
True
: if the object appears callableFalse
: if the object is not callable.
danger
- Even if
callable()
isTrue
, call to the object may still fail. - However, if
callable()
returnsFalse
, call to the object will certainly fail.
Examples
Basic Example
A normal variable is not callable while a function is callable.
x = 123
print(callable(x))
def testFunction():
print("Test")
y = testFunction
print(callable(y))
output
False
True
Example of callable object
class Foo:
def __call__(self):
print('I am callable')
print(callable(Foo))
output
True
Also, the instance of our Foo
class appears to be callable (and is callable in this case):
class Foo:
def __call__(self):
print('I am callable')
InstanceOfFoo = Foo()
print(callable(InstanceOfFoo)) # Prints True
InstanceOfFoo() # Prints 'I am callable'
output
True
I am callable
Example of object that appears to be callable but it is not callable
class Foo:
def printLine(self):
print('I am callable')
print(callable(Foo))
output
True
The instance of Foo
class appears to be callable but it's not callable. In fact, the following code will raise an error:
class Foo:
def printLine(self):
print('Print Something')
print(callable(Foo))
InstanceOfFoo = Foo()
InstanceOfFoo() # Error!
output
True
Traceback (most recent call last):
File "main.py", line 8, in <module>
InstanceOfFoo()
TypeError: 'Foo' object is not callable