ZetCode

Python __call__ Method

Last modified November 17, 2026 Python 3.15

An object is callable when it can be used with the function call syntax obj(args). Functions, built-in types, and classes are callable, and so is any instance whose class defines the __call__ method. This article explains how the interpreter decides whether an object is callable, how arguments reach __call__, and which patterns justify a callable object instead of a plain function.

What makes an object callable

The callable() function reports whether an object can be called, and the answer depends on the type of the object, not on its instance dictionary. A class is callable because its type is type, which implements __call__ to create instances. An instance is callable when its class defines __call__, including a definition inherited from a base class.

callable_forms.py
class Plain:
    pass


class Callable:
    def __call__(self):
        return "called"


def func():
    return "called"


for obj in (func, Plain, Plain(), Callable(), Callable):
    print(f"{type(obj).__name__:9} callable={callable(obj)}")

A function and a class are always callable. An instance of Plain is not, because neither Plain nor object defines __call__. An instance of Callable is callable, and the class itself reports type as its type, which is the metaclass that creates instances.

$ python callable_forms.py
function  callable=True
type      callable=True
Plain     callable=False
Callable  callable=True
type      callable=True

A basic __call__ method

__call__ is an ordinary method that receives the instance as its first argument, followed by whatever arguments the caller supplies. Positional, keyword-only, and default arguments all work exactly as they do in a normal function, and inspect.signature() can read them from the bound method.

greeter.py
class Greeter:
    def __init__(self, greeting):
        self.greeting = greeting

    def __call__(self, name, punctuation="!"):
        return f"{self.greeting}, {name}{punctuation}"


hello = Greeter("Hello")

print(hello("Alice"))
print(hello("Bob", "."))
print(hello.__dict__)

The instance keeps the greeting in its own attribute, so one class can produce any number of differently configured callables. The call itself does not modify the object; hello.__dict__ still contains only the greeting after two calls.

$ python greeter.py
Hello, Alice!
Hello, Bob.
{'greeting': 'Hello'}

Keeping state between calls

The main reason to use a callable object instead of a function is state. A closure can hide one variable, but an object exposes its state as attributes, supports several independent instances, and can grow methods for inspection and reset. The following example implements the same counter both ways.

counter.py
class Counter:
    def __init__(self):
        self.count = 0

    def __call__(self):
        self.count += 1
        return self.count


def make_counter():
    count = 0

    def counter():
        nonlocal count
        count += 1
        return count

    return counter


c = Counter()
print(c(), c(), c(), c.count)

d = Counter()
print(d(), c.count)

f = make_counter()
print(f(), f())
try:
    print(f.count)
except AttributeError as e:
    print(type(e).__name__, e)

Each Counter instance has its own count, so d() returns 1 while c.count stays at 3. The closure counts correctly too, but the count cannot be read or reset without adding more functions. The instance attribute is part of the public interface, which is often what makes the object version easier to test and debug.

$ python counter.py
1 2 3 3
1 3
1 2
AttributeError 'function' object has no attribute 'count'

Class-based decorators

A class decorator is a class that receives a function in __init__ and wraps it in __call__. Because the wrapper is an instance, it can count calls, record arguments, or cache results. The functools.update_wrapper() call copies __name__, __doc__, and other metadata from the wrapped function so the decorated object still looks like the original.

decorator_trace.py
import functools


class Trace:
    def __init__(self, func):
        self.func = func
        self.calls = 0
        functools.update_wrapper(self, func)

    def __call__(self, *args, **kwargs):
        self.calls += 1
        shown = ", ".join(map(repr, args))
        print(f"call {self.calls}: {self.func.__name__}({shown})")
        return self.func(*args, **kwargs)


@Trace
def square(x):
    """Return x squared."""
    return x * x


print(square.__name__)
print(square.__doc__)
print(square(5))
print(square(3))
print(square.calls)

@Trace replaces the function with a Trace instance, and every later call goes through __call__. Without update_wrapper, square.__name__ would be missing and help tools would show the wrapper instead of the original function. The counter is stored on the instance, so it survives between calls but stays private to this decorated function.

$ python decorator_trace.py
square
Return x squared.
call 1: square(5)
25
call 2: square(3)
9
2

Memoization

A memoizer stores results by argument tuple and returns the cached value on a repeated call. The recursive call inside fib looks up the module name fib, which now refers to the Memoize instance, so the cache is used at every level of the recursion.

memoize.py
import functools


class Memoize:
    def __init__(self, func):
        self.func = func
        self.cache = {}
        functools.update_wrapper(self, func)

    def __call__(self, *args):
        if args not in self.cache:
            print(f"computing {self.func.__name__}{args}")
            self.cache[args] = self.func(*args)
        return self.cache[args]


@Memoize
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)


print(fib(10))
print(fib(10))
print(len(fib.cache))

The first call computes each value from 10 down to 0 exactly once. The second call to fib(10) finds the result in the cache and prints nothing, and the cache holds 11 entries. Arguments must be hashable for this design; a list argument would fail when the tuple is used as a dictionary key.

$ python memoize.py
computing fib(10,)
computing fib(9,)
computing fib(8,)
computing fib(7,)
computing fib(6,)
computing fib(5,)
computing fib(4,)
computing fib(3,)
computing fib(2,)
computing fib(1,)
computing fib(0,)
55
55
11

Callables as strategies

Many library functions accept a callable and call it later: sorted with key, map, filter, and min or max with key. A small callable object can carry configuration for such a strategy, and it can be reused or replaced without changing the calling code.

strategies.py
class Sorter:
    def __init__(self, key):
        self.key = key

    def __call__(self, item):
        return self.key(item)


words = ["banana", "kiwi", "apple", "fig"]
by_length = Sorter(len)
by_last = Sorter(lambda w: w[-1])

print(sorted(words, key=by_length))
print(sorted(words, key=by_last))
print(min(words, key=by_length))

# a plain function works the same way
print(sorted(words, key=len))

Sorter adds nothing that len does not already do, and the last line shows that a plain function is enough for a stateless key. The object form becomes useful when the key needs parameters, for example a Sorter that ignores case or reads a column index, because the configuration lives in the instance instead of in a global or a lambda.

$ python strategies.py
['fig', 'kiwi', 'apple', 'banana']
['banana', 'apple', 'fig', 'kiwi']
fig
['fig', 'kiwi', 'apple', 'banana']

Lookup rules and pitfalls

Special methods are looked up on the type, so adding __call__ to an instance dictionary does not make that instance callable. The reverse is also true: setting obj.__call__ to None hides the method from normal attribute access but does not disable the call operator.

lookup.py
class WithCall:
    def __call__(self, x):
        return x + 1


class WithoutCall:
    pass


obj = WithCall()
obj.__call__ = None            # instance attribute

print(callable(obj))
print(obj.__call__)
print(obj(1))

plain = WithoutCall()
plain.__call__ = lambda: "from instance dict"
print(callable(plain))
try:
    print(plain())
except TypeError as e:
    print(type(e).__name__, e)

The first object stays callable because WithCall.__call__ is still found on the type, even though the instance attribute shadows it for direct attribute access. The second object remains non-callable, because the lambda lives only in the instance dictionary. If code needs to disable calling, it must change the class or remove the behaviour some other way.

$ python lookup.py
True
None
2
False
TypeError 'WithoutCall' object is not callable

Best practices

A callable object is a small interface, so treat it like one:

Source

object.__call__ - Python documentation

callable() - Python documentation

functools.update_wrapper - Python documentation

In this article we have implemented the __call__ method. We have covered callable detection, argument handling, stateful counters, class-based decorators, memoization, strategy objects, and the type-level lookup rule. For related topics, see Python call method, Python callable built-in, Python __init__ method, Python __new__ method, and Python decorators.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.