How to Check If an Object Is Callable in Python
In Python, a callable is any object that can be invoked using parentheses (). This includes standard functions, methods, classes, and even class instances if they define a specific magic method.
Attempting to call an object that is not callable (like an integer or a string) results in a TypeError. This guide explains how to safely determine if an object is callable using the built-in callable() function and how to handle invocation errors gracefully.
Understanding the Error: Not Callable
In Python, you can assign functions to variables. However, this flexibility can lead to bugs where a variable is expected to be a function but actually holds a data type like an int or None.
If you try to "call" a non-callable object, Python raises a TypeError.
def my_function():
return "I am a function"
# Assigning an integer to a variable
not_a_function = 42
try:
# ⛔️ Incorrect: Trying to call an integer like a function
result = not_a_function()
print(result)
except TypeError as e:
print(f"Error: {e}")
Output:
Error: 'int' object is not callable
Method 1: Using the callable() Function (Recommended)
The most Pythonic way to check if an object can be called is using the built-in callable() function. It returns True if the object appears callable, and False otherwise.
checking Functions and Variables
def greet():
return "Hello!"
name = "Alice"
# ✅ Correct: Check before calling
if callable(greet):
print(f"greet is callable. Result: {greet()}")
if not callable(name):
print(f"name is NOT callable. It is type: {type(name)}")
Output:
greet is callable. Result: Hello!
name is NOT callable. It is type: <class 'str'>
Checking Classes and Methods
Classes are callable (calling them creates an instance), and methods are callable.
class Dog:
def bark(self):
return "Woof!"
# Classes are callable (the constructor)
print(f"Is class Dog callable? {callable(Dog)}")
# Methods are callable
my_dog = Dog()
print(f"Is method .bark callable? {callable(my_dog.bark)}")
# Instances are usually NOT callable (unless __call__ is defined)
print(f"Is instance my_dog callable? {callable(my_dog)}")
Output:
Is class Dog callable? True
Is method .bark callable? True
Is instance my_dog callable? False
The callable() function is generally reliable. If it returns True, the object usually works with (), though it might still fail if the function raises an internal error.
Method 2: Handling Invocation with try-except
Python often follows the EAFP principle (Easier to Ask for Forgiveness than Permission). Instead of checking if callable(x), you can try to call it and catch the TypeError.
This is useful when you expect the object to be callable 99% of the time and want to handle the edge case.
def safe_execute(obj):
try:
# ✅ Try to call the object
return obj()
except TypeError as e:
# Handle the specific error string for non-callables
if "not callable" in str(e):
print(f"Failed: Object '{obj}' is not callable.")
else:
# Re-raise if it was a different TypeError inside the function
raise e
x = 100
safe_execute(x)
Output:
Failed: Object '100' is not callable.
Be careful with try-except TypeError. A TypeError can also occur inside the function you are calling (e.g., passing wrong arguments). Ensure you are catching the error for the object being non-callable, not an error within the logic itself.
Advanced: Making Custom Classes Callable
You can make your own class instances callable by implementing the __call__ magic method.
class Multiplier:
def __init__(self, factor):
self.factor = factor
# ✅ Define __call__ to make instances callable
def __call__(self, number):
return number * self.factor
# Create an instance
double = Multiplier(2)
# Check callability
print(f"Is 'double' instance callable? {callable(double)}")
# Invoke the instance as if it were a function
print(f"Result: {double(10)}")
Output:
Is 'double' instance callable? True
Result: 20
Conclusion
To determine if an object can be invoked in Python:
- Use
callable(obj)for a safe, boolean check. This is the standard approach for conditional logic. - Use
try-except TypeErrorif you prefer to attempt execution immediately and handle failures (EAFP). - Implement
__call__in your classes if you want instances to behave like functions.