🕯️ Magic Note
An object is callable if it defines the __call__ method. This includes all functions (built in and user defined), methods, classes, and instances of classes that implement __call__. Even objects that are not normally considered functions can be callable. The callable() function checks for this internal method without executing anything.
- Returns True for built in functions like print() and len()
- Returns True for user defined functions defined with def or lambda
- Returns True for classes and methods
- Returns True for instances with a __call__ method
- Returns False for most data types (int, str, list, dict, tuple, set)
| Object | Type | callable() |
|---|---|---|
| built in function | True | |
| len | built in function | True |
| lambda x: x*2 | lambda function | True |
| class MyClass: pass | class | True |
| str | class (callable constructor) | True |
| “My string” | string instance | False |
| 42 | integer | False |
| [“list”] | list | False |
| obj.method | bound method | True |
Python
# Checking callable objects
def my_function():
return “Hello”
class MyClass:
pass
print(callable(my_function))
# Output: True
print(callable(MyClass))
# Output: True
print(callable(print))
# Output: True
Python
# Checking non callable objects
number = 42
text = “whisper”
items = [1, 2, 3]
mapping = {“key”: “value”}
print(callable(number))
# Output: False
print(callable(text))
# Output: False
print(callable(items))
# Output: False
print(callable(mapping))
# Output: False
Python
# Creating a callable instance with __call__
class CallableSpell:
def __call__(self, name):
return f”Abracadabra, {name}!”
spell = CallableSpell()
print(callable(spell))
# Output: True
print(spell(“Feloriya”))
# Output: Abracadabra, Feloriya!
# Without __call__, the instance is not callable
class SilentSpell:
pass
silent = SilentSpell()
print(callable(silent))
# Output: False
- Assuming callable() tries to call the object, it only checks without executing
- Forgetting that classes are callable (they create instances), so callable(MyClass) returns True
- Thinking callable() guarantees a successful call, arguments must still be correct
⚡ Whisper
Not everything in the code answers when you call. Some objects stand silent, holding data without voice. Others wake at the sound of parentheses, ready to execute. Listen first. Ask the quiet question. Then call only those who respond.