callable()
Returns True if an object can be called with brackets, like a function, method or class, and False for plain values such as numbers.
callable(object)In Python you call something by putting brackets after it: print(), len(x), Dog(). callable(obj) tells you whether obj(...) could work at all, without trying it.
Functions, methods, lambdas and classes are callable. Numbers, strings, lists and most objects are not. An object of your own class becomes callable if the class defines a __call__ method.
It is handy when a parameter may be either a fixed value or a function that produces the value. Note that True only means "this can be called", not that the call will succeed with the arguments you plan to pass.
Parameters
| Parameter | What it is |
|---|---|
objectrequired | Any value. |
Return value
True or False.
Examples
1Functions vs values
def greet():
return "hi"
print(callable(greet))
print(callable(print))
print(callable(greet()))
print(callable(42))True True False False
greet is the function; greet() is the string it returns, and a string cannot be called.
2Classes are callable, their objects usually not
Calling a class creates a new object, so the class itself is callable.
class Dog:
def bark(self):
return "Woof"
rex = Dog()
print(callable(Dog))
print(callable(rex))
print(callable(rex.bark))True False True
3Make your own objects callable with __call__
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, number):
return number * self.factor
double = Multiplier(2)
print(callable(double))
print(double(21))True 42
4Accept a value or a function
A setting can be a fixed number, or a function that works the number out. callable() tells them apart.
def get_discount(discount, price):
if callable(discount):
return discount(price)
return discount
print(get_discount(5, 80))
print(get_discount(lambda p: p * 0.1, 80))5 8.0
Common mistakes
Passing the result instead of the function
callable(func()) checks what the function returned. Leave out the brackets to check the function itself.
def today_menu():
return "soup"
print(callable(today_menu()))
print(callable(today_menu))False True
Thinking callable() means the call will work
callable(len) is True, yet len(5) still raises TypeError. callable() checks only that brackets are allowed, not the arguments.
Questions people ask
How do I check if a variable is a function?
callable(x) is the simplest test and also accepts methods, classes and lambdas. To accept only functions defined with def or lambda, use inspect.isfunction(x).
Why do I get "object is not callable"?
You put brackets after something that is not a function, often because a variable has the same name as a function: sum = 10 and later sum(items). Rename the variable.
Are classes callable?
Yes. Calling a class creates an instance, so callable(MyClass) is True.