Sub topic 13
Callable objects with __call__
This chapter assumes you can define classes and methods, know how instance attributes work, and have used functions as values (passing them as arguments, for example). Earlier chapters covered how Python maps syntax to special methods. Here the syntax is the call expression obj(...).
How a call maps to __call__
When you write f(1, 2), Python looks up __call__ on the type of f and invokes it. For a function, that method is built in. For an instance of your own class, you supply it.
class Greeter:
def __init__(self, greeting):
self.greeting = greeting
def __call__(self, name):
return f'{self.greeting}, {name}!'
hello = Greeter('Hello')
print(hello('Ada')) # Hello, Ada!
print(hello.__call__('Ada')) # Hello, Ada!
print(callable(hello)) # Truehello('Ada') and hello.__call__('Ada') do the same thing. You normally write the first form.
The method accepts any signature you choose: positional arguments, keywords, defaults, *args, and **kwargs. The instance is passed as self, like any other method.
Why use an object instead of a function
A plain function is the right choice for most tasks. A callable object is useful when the thing you call needs one or more of these:
- State that persists between calls, such as a counter, a cache, or a running total.
- Configuration set once and reused, such as a threshold or a prefix.
- Several related methods alongside the call, such as
reset()orstats(). - A place to hold a resource, such as a compiled regular expression or a loaded model.
Many APIs only require "something callable": map, sorted(key=...), threading.Thread(target=...), callbacks in GUI and web frameworks, and decorators. A callable object fits all of them.
State between calls
The chapter's basic example is a counter. It keeps its count on the instance.
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 instance has its own state, so two counters do not interfere:
a = Counter()
b = Counter()
a()
a()
print(a.count, b.count) # 2 0You could get similar behavior from a closure that uses nonlocal. The class version makes the state visible (tick.count) and lets you add methods. The closure version is shorter when you need neither.
Configured callables with sorted and map
A callable object can carry settings and be passed anywhere a function is expected.
class Threshold:
def __init__(self, limit):
self.limit = limit
def __call__(self, value):
return value > self.limit
above_10 = Threshold(10)
print(list(filter(above_10, [4, 12, 9, 30]))) # [12, 30]filter only needs a callable that takes one value and returns a truthy or falsy result. It does not care whether that is a function, a lambda, or a Threshold instance.
functools.partial covers the simple case of fixing some arguments of an existing function. Prefer a class when you want state, extra methods, or a readable __repr__.
A memoizing callable
Caching results is a common use. The object stores the cache and the wrapped function.
class Memo:
def __init__(self, func):
self.func = func
self.cache = {}
self.hits = 0
def __call__(self, *args):
if args in self.cache:
self.hits += 1
return self.cache[args]
result = self.func(*args)
self.cache[args] = result
return result
def __repr__(self):
return f'Memo({self.func.__name__}, cached={len(self.cache)})'
def slow_square(n):
return n * n
fast = Memo(slow_square)
print(fast(4)) # 16
print(fast(4)) # 16, served from the cache
print(fast.hits) # 1
print(fast) # Memo(slow_square, cached=1)Arguments become dictionary keys, so they must be hashable. Calling fast([1, 2]) raises TypeError: unhashable type: 'list'. The standard library's functools.lru_cache handles this for real code, including a size limit. The class here shows the mechanism.
Callable objects as decorators
A decorator is any callable that takes a function and returns a callable. Memo above works directly:
@Memo
def cube(n):
return n ** 3
print(cube(3)) # 27
print(cube(3)) # 27
print(cube.hits) # 1@Memo is shorthand for cube = Memo(cube). After decoration, cube is a Memo instance, not a function. That has two consequences:
- The original name and docstring are not copied over.
cube.__name__raisesAttributeError, because the instance has no such attribute. Callfunctools.update_wrapper(self, func)in__init__to copy__name__,__doc__, and related attributes. - Decorating a method this way breaks binding. See the next section.
A decorator that takes arguments uses two stages: the class constructor receives the settings, and __call__ receives the function.
import functools
class Repeat:
def __init__(self, times):
self.times = times
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = None
for _ in range(self.times):
result = func(*args, **kwargs)
return result
return wrapper
@Repeat(3)
def shout(text):
print(text.upper())
shout('hey') # prints HEY three timesRepeat(3) builds an instance. Python then calls that instance with shout, and the result replaces shout.
Gotcha: callable instances are not bound as methods
Functions defined in a class body become bound methods when accessed through an instance, because functions implement the descriptor protocol (__get__). An instance of your callable class does not, unless you add __get__.
class Doubler:
def __call__(self, x):
return x * 2
class Shape:
double = Doubler()
s = Shape()
print(s.double(4)) # 8Here Doubler.__call__ receives x=4. The Shape instance s is not passed anywhere. If you expected s to arrive as the first argument, as it would with a normal method, it will not. A decorator class applied to a method has this same problem: self of the method never reaches the wrapped function.
To support methods, the callable class must define __get__ and return a bound version. That is the descriptor mechanism covered in a later chapter. For a decorator on methods, a function-based decorator with functools.wraps is usually simpler.
Gotcha: __call__ is looked up on the type
Python finds __call__ on type(obj), not on the instance. Assigning a function to an instance attribute does not make the instance callable.
class Plain:
pass
p = Plain()
p.__call__ = lambda: 'hi'
print(callable(p)) # False
try:
p()
except TypeError as e:
print(e) # 'Plain' object is not callableThe same rule applies to every special method. Define it in the class body. If you need per-instance behavior, store a function as a normal attribute and have the class's __call__ delegate to it:
class Hook:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
h = Hook(lambda n: n + 1)
print(h(1)) # 2Classes are callable too
Every class is itself callable. Vector(1, 2) calls type(Vector).__call__, which is type.__call__. That method runs __new__ and then __init__, as the earlier chapter on object creation described. So callable(int), callable(list), and callable(Vector) are all True.
This is why callable() alone cannot tell you whether something is a function. Use inspect.isfunction or isinstance(x, types.FunctionType) if you need that distinction.
Guidelines for __call__
- Give the call one clear meaning. A
Thresholdthat tests a value is clear. An object whose call sometimes computes, sometimes resets, and sometimes saves is not. - Keep the signature stable. Callers pass the object to code that assumes a particular argument shape.
- Prefer a regular named method when the action is not the object's single main job.
parser.parse(text)is clearer thanparser(text)if the parser does other things. - Add a
__repr__to callable objects. A debugging message that says<__main__.Memo object at 0x...>tells you little. - If the state is shared across threads, protect it.
Counterabove is not thread-safe, becauseself.count += stepis not atomic.
Summary of the mapping
| Syntax | Method looked up on the type |
|---|---|
| `obj(1, key=2)` | `type(obj).__call__(obj, 1, key=2)` |
| `callable(obj)` | checks whether the type defines `__call__` |
| `Cls(1)` | `type(Cls).__call__(Cls, 1)`, which runs `__new__` and `__init__` |
Exercise
Write a class RunningAverage whose instances are called with a number, add it to the running total, and return the average of all numbers passed so far. Then explain why ra = RunningAverage(); ra.__call__ = lambda x: 0 does not change what ra(5) does.
Show answer
class RunningAverage:
def _init(self):
self.total = 0
self.n = 0
def call(self, value):
self.total += value
self.n += 1
return self.total / self.n
ra = RunningAverage()
print(ra(10)) # 10.0
print(ra(20)) # 15.0
Python looks up `call_ on the type, RunningAverage, not on the instance. The instance attribute is ignored by the call expression, so ra(5)` still runs the class's method and returns 5 / 3 style averages as before.
Exercise
A decorator class Log has __init__(self, func) and a __call__(self, *args) that prints the arguments and calls func. It works on a plain function but fails on a method in a class. Why, and what is a simple fix?
Show answer
Instances of Log are not functions, so they have no __get__ and are not bound when accessed through an instance. The method's self is never passed to the wrapped function, so the arguments are shifted and the call fails or misbehaves. A simple fix is to write the decorator as a function that returns an inner function wrapped with functools.wraps, since functions bind as methods. Alternatively, add a __get__ to Log that returns functools.partial(self, instance).