Python callable()
Function
The callable() function in Python checks whether an object can be called like a function. It returns True
if the object appears callable (such as a function, method, class, or object with a __call__()
method), otherwise it returns False
.
Syntax
callable(object)
Parameter:
object
– Any Python object (function, class, variable, etc.)
Returns:
True
if the object is callableFalse
otherwise
Example 1: Function is Callable
def greet():
print("Hello!")
print(callable(greet))
True
Why? Because greet
is a function, and functions are callable.
Example 2: Integer is Not Callable
x = 42
print(callable(x))
False
Why? Because integers are not callable.
Example 3: Class is Callable
class Person:
pass
print(callable(Person))
True
Why? Because classes can be called to create new instances.
Example 4: Object with __call__
is Callable
class MyClass:
def __call__(self):
print("I can be called!")
obj = MyClass()
print(callable(obj))
True
Why? Because the object defines a __call__()
method.
Use Cases
- To check before calling a function dynamically (like in decorators or plugins)
- To verify if an object supports being used like a function
- Used in frameworks to ensure interfaces are implemented correctly
Common Mistakes
- Confusing "callable" with “instance of function” — classes and objects with
__call__()
are callable too! - Trying to call non-callable objects like strings or numbers leads to
TypeError
Interview Tip
In advanced Python coding rounds, callable objects and the __call__()
method are often tested to assess your understanding of OOP and metaprogramming.
Summary
callable(obj)
returnsTrue
if the object can be called like a function.- Functions, classes, and objects with
__call__()
are callable. - Numbers, strings, lists, etc., are not callable.
Practice Problem
Create a class called Counter
that behaves like a function and prints "Counting..." when called. Use callable()
to check the object.
class Counter:
def __call__(self):
print("Counting...")
c = Counter()
print(callable(c))
c()
True
Counting...
Comments
Loading comments...