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"
not_a_function = 42
try:
result = not_a_function()
print(result)
except TypeError as e:
print(f"Error: {e}")Output:
Error: 'int' object is not callableMethod 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"
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!"
print(f"Is class Dog callable? {callable(Dog)}")
my_dog = Dog()
print(f"Is method .bark callable? {callable(my_dog.bark)}")
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? FalseMethod 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:
return obj()
except TypeError as e:
if "not callable" in str(e):
print(f"Failed: Object '{obj}' is not callable.")
else:
raise e
x = 100
safe_execute(x)Output:
Failed: Object '100' is not callable.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
def __call__(self, number):
return number * self.factor
double = Multiplier(2)
print(f"Is 'double' instance callable? {callable(double)}")
print(f"Result: {double(10)}")Output:
Is 'double' instance callable? True
Result: 20Conclusion
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.