Can an object be used with parentheses? Python’s built-in callable checks whether an object can be invoked with the call operator (). Functions and classes are callable; ordinary instances are not necessarily callable. section 10.5 section 10.5.4
Check a function
def doubler(x): return 2 * x assert callable(doubler) The assertion passes because doubler is a function and can be called as doubler(3). section 10.5
Callability does not mean “function.” Calling a class creates an instance, while calling a function performs its defined operation. For example, dict and range are classes, whereas callable and hash are functions. Either kind of object can be passed where a callable is expected, such as the key argument to sorted. section 10.5.1 section 10.5.3
Use a class as a sorting key
cards = [10, 1, 'J', 'A'] print(sorted(cards, key=str)) # [1, 10, 'A', 'J'] Converting each card to a string permits sorting but puts A before J. A class that converts face cards to numeric ranks can instead serve as the key: class PokerOrder(int): def __new__(cls, x): ranks = {'J': 11, 'Q': 12, 'K': 13, 'A': 14} return super().__new__(cls, ranks.get(x, x)) print(sorted(cards, key=PokerOrder)) # [1, 10, 'J', 'A'] section 10.5.3
A custom instance can also become callable by implementing __call__. This makes a class-based decorator possible: the class receives the decorated function, and its instance handles later calls. Unlike a function-based decorator, the decorated name then refers to an instance, which can hold additional attributes. section 10.5.4 section 10.5.5
import time
class TimeLogger:
def __init__(self, func):
def logger(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"Calling {func.__name__}: {time.time() - start:.5f}")
return result
self._logger = logger
def __call__(self, *args, **kwargs):
return self._logger(*args, **kwargs)
TimeLogger stores a logging function on the instance and forwards calls through __call__, making that instance usable as a decorator result. section 10.5.4




