Sub topic 13
Callable objects with __call__
This chapter assumes you can define classes, write instance methods, and use functions as values. It builds on the data model chapter, where syntax maps to special methods on an object's type.
How a call becomes a method
When you write obj(args), Python looks up __call__ on type(obj) and runs type(obj).__call__(obj, args). Any object whose class defines __call__ is callable. Functions are callable the same way, because the function type defines __call__.
The built-in callable() reports whether an object can be called. It checks the type, not the instance.
A stateful callable
A plain function forgets everything between calls unless you use globals or closures. A callable object keeps its state in attributes.
class Counter:
def __init__(self):
self.count = 0
def __call__(self, step=1):
self.count += step
return self.count
tick = Counter()
print(tick()) # 1
print(tick(5)) # 6
print(callable(tick)) # TrueEach Counter() has its own count, so two counters never interfere. __call__ accepts any signature you choose, including keyword arguments and *args.
Configured callables
A common use is an object that is configured once and then applied many times. The constructor stores the settings, and __call__ does the work. This works well wherever an API expects a function, such as the key argument of sorted().
class Scaler:
def __init__(self, factor):
self.factor = factor
def __call__(self, value):
return value * self.factor
double = Scaler(2)
print(list(map(double, [1, 2, 3]))) # [2, 4, 6]
print(sorted([3, -5, 1], key=lambda n: abs(n))) # [1, 3, -5]Compared with a closure, a callable class is easier to inspect, since you can read double.factor. It can also carry extra methods and a useful __repr__.
Common errors
- Calling the class instead of the instance.
Counter()creates an object.tick()calls it. WritingCounter(5)passes5to__init__, not to__call__. - Defining
__call__on the instance. Settingtick.__call__ = somethinghas no effect ontick(), because Python looks on the type. Define it in the class body. - Forgetting
self.def __call__(step)binds the instance tostepand fails with a confusing argument error. - Hidden side effects. A callable that changes state on every call can surprise callers who expect a pure function. Document it, or expose the state as an attribute, as
Counterdoes.
The next diagram shows the lookup path.
Exercise
Write a class Greeter that is created with a greeting such as "Hello" and, when called with a name, returns the greeting followed by a comma, a space, and the name. What does Greeter("Hi")("Ana") return?
Show answer
class Greeter: def _init(self, greeting): self.greeting = greeting def call(self, name): return f'{self.greeting}, {name}' Greeter("Hi")("Ana") returns 'Hi, Ana'. The first pair of parentheses calls the class and runs init. The second pair calls the new instance and runs call_.