Python callable() function is a simple way to check if something can be called like a function. It returns True
if the object you give it is something you can put parentheses after and execute, like a function or a method. Otherwise, it returns False
.
callable()
Syntax
is_callable = callable(object)
Code Explanation
is_callable
: A variable to store the result (True or False).callable()
: The built-in Python function for the check.object
: The thing you want to see if you can “call”.
Example 1: Callable Function Check with Python callable()
def my_function():
print("Hello!")
result = callable(my_function)
print(result)
Code Explanation
- Lines 1-2: Defines a simple function.
- Line 4: Checks if
my_function
is callable. - Line 5: Prints
True
because functions are callable.
Output
True
Example 2: Callable Object Check with Python callable()
class MyClass:
def my_method(self):
print("I'm a method!")
obj = MyClass()
result = callable(obj.my_method)
print(result)
Code Explanation
- Lines 1-3: Defines a class with a method.
- Line 5: Creates an object of that class.
- Line 6: Checks if the object’s method is callable.
- Line 7: Prints
True
because methods are callable.
Output
True
Example 3: Object Appears Callable but Isn’t
class MyClass:
def __call__(self): # Special method to make objects "callable"
print("Called like a function!")
obj = MyClass()
result1 = callable(obj)
result2 = callable(obj.my_method) # Assuming 'my_method' doesn't exist
Code Explanation
- Lines 1-3: Defines a class with the special
__call__
method. - Line 5: Creates an object.
- Line 6: The object itself is callable due to
__call__
. - Line 7: Tries to check a non-existent method, causing an error and demonstrating that not everything on an object is callable.
Output
True
False
Example 4: Callable Built-in Function Check with Python callable()
result = callable(print)
print(result)
Code Explanation
- Line 1: Directly checks if the built-in
print
function is callable. - Line 2: Prints
True
as expected.
Output
True
Example 5: Callable String Check with Python callable()
result = callable("hello")
print(result)
Code Explanation
- Line 1: Checks if a string is callable
- Line 2: Prints
False
because strings are not callable
Output
False