ZetCode

Python callable objects

last modified November 30, 2026 Python 3.15

In this article we show how to use callable objects in Python programs.

An object is callable when its class defines the __call__ method; calling the object as obj(args) runs that method. A callable object can be passed anywhere a function is expected, but unlike a function it can carry configuration and state in its attributes and offer additional methods.

How the __call__ method works, and simple examples such as counters and memoization, are covered in Python __call__ method. The Python callable function article explains how to test whether an object can be called. This article focuses on the uses of callable objects in larger programs.

A configurable function

The simplest use of a callable object is a function with settings. The settings are given once when the object is created, and the object is then called like a function.

tax.py
class Tax:

    def __init__(self, rate):
        self.rate = rate

    def __call__(self, price):
        return round(price * (1 + self.rate), 2)


vat = Tax(0.20)
reduced = Tax(0.05)

print(vat(100), reduced(100))

prices = [9.99, 24.50, 120.00]
print(list(map(vat, prices)))
print(list(map(reduced, prices)))

Each Tax object stores its own rate. The objects vat and reduced are called with a price, just like functions, and they can be passed to map, which only requires something it can call.

$ python tax.py
120.0 105.0
[11.99, 29.4, 144.0]
[10.49, 25.73, 126.0]

Callables with extra methods

A callable object is still an object. Besides being called, it can offer methods for configuring it and attributes for inspecting it, which a plain function cannot do easily.

validator.py
class Validator:

    def __init__(self, name):
        self.name = name
        self.rules = []
        self.errors = []

    def rule(self, message, check):
        self.rules.append((message, check))
        return self

    def __call__(self, value):
        failed = [msg for msg, check in self.rules if not check(value)]
        self.errors.extend(f"{value!r}: {msg}" for msg in failed)
        return not failed

    def clear(self):
        self.errors.clear()


username = (Validator("username")
            .rule("too short", lambda s: len(s) >= 3)
            .rule("not alphanumeric", str.isalnum))

names = ["jmartin", "al", "x-y", "lucia99"]
valid = list(filter(username, names))

print(valid)
print(len(username.rules), "rules")
for error in username.errors:
    print(error)

username.clear()
print(username("bo"), username.errors)

A Validator is built with the rule method, which returns the object itself so that calls can be chained. Calling the validator checks a value against all rules and returns True or False, so the object works as a predicate for filter. The failed checks are collected in the errors attribute, which can be read and cleared afterwards.

$ python validator.py
['jmartin', 'lucia99']
2 rules
'al': too short
'x-y': not alphanumeric
False ["'bo': too short"]

Callbacks

Code that accepts a callback should not care what kind of callable it gets. Functions, lambdas, bound methods, partial objects, and callable instances can all be used together.

callbacks.py
import functools


class Counter:

    def __init__(self):
        self.count = 0

    def __call__(self, event):
        self.count += 1


class Logger:

    def __init__(self, prefix):
        self.prefix = prefix

    def write(self, event):
        print(f"{self.prefix} {event}")


def notify(channel, event):
    print(f"[{channel}] {event}")


class EventBus:

    def __init__(self):
        self.handlers = []

    def subscribe(self, handler):
        if not callable(handler):
            raise TypeError(f"{handler!r} is not callable")
        self.handlers.append(handler)

    def publish(self, event):
        for handler in self.handlers:
            handler(event)


counter = Counter()
bus = EventBus()

bus.subscribe(counter)
bus.subscribe(Logger("log:").write)
bus.subscribe(functools.partial(notify, "email"))
bus.subscribe(lambda event: print("length", len(event)))

bus.publish("user registered")
bus.publish("order paid")
print("events counted:", counter.count)

try:
    bus.subscribe("print")
except TypeError as e:
    print(e)

The EventBus calls each subscribed handler with the event. The handlers are of four kinds: a Counter instance, the bound method Logger("log:").write, a functools.partial object that fixes the first argument of notify, and a lambda. The bus only checks with callable that a handler can be called; the string "print" is rejected. The counter keeps its state between events, and the state can be read afterwards.

$ python callbacks.py
log: user registered
[email] user registered
length 15
log: order paid
[email] order paid
length 10
events counted: 2
'print' is not callable

A decorator class with arguments

A decorator can be written as a class. When the decorator takes arguments, __init__ receives the arguments and __call__ receives the function to decorate.

limit.py
import functools


class Limit:

    def __init__(self, max_calls):
        self.max_calls = max_calls
        self.calls = 0

    def __call__(self, func):

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if self.calls >= self.max_calls:
                raise RuntimeError(f"{func.__name__}: limit of "
                                   f"{self.max_calls} calls reached")
            self.calls += 1
            return func(*args, **kwargs)

        return wrapper

    def reset(self):
        self.calls = 0


sms_limit = Limit(2)


@sms_limit
def send_sms(number, text):
    print(f"to {number}: {text}")


for text in ["first", "second", "third"]:
    try:
        send_sms("555-0100", text)
    except RuntimeError as e:
        print(e)

print(sms_limit.calls, send_sms.__name__)
sms_limit.reset()
send_sms("555-0100", "after reset")

Limit(2) creates an object holding the limit and a call count. Applying it with @sms_limit calls its __call__ method with send_sms, and the method returns a wrapper function that checks the limit before each call. The decorator object stays accessible under its own name, so the program can read its counter and reset it, which would require extra work with a decorator written as nested functions. Function decorators are explained in Python decorators.

$ python limit.py
to 555-0100: first
to 555-0100: second
send_sms: limit of 2 calls reached
2 send_sms
to 555-0100: after reset

Decorating methods

A class used directly as a decorator replaces the function with an instance of the class. This works for functions, but it breaks when the decorated function is a method.

method_problem.py
import functools


class Trace:

    def __init__(self, func):
        functools.update_wrapper(self, func)
        self.func = func

    def __call__(self, *args, **kwargs):
        print(f"calling {self.func.__name__} with {args}")
        return self.func(*args, **kwargs)


@Trace
def double(x):
    return x * 2


class Account:

    def __init__(self, balance):
        self.balance = balance

    @Trace
    def deposit(self, amount):
        self.balance += amount


print(double(21))

acc = Account(100)
try:
    acc.deposit(50)
except TypeError as e:
    print(e)

The decorated double function works. The decorated deposit method does not: acc.deposit finds a Trace object in the class and calls it with (50,) only. An ordinary function stored in a class becomes a bound method when accessed through an instance, which passes the instance as self. Instances of our class do not do that, so deposit receives 50 as self and no amount.

$ python method_problem.py
calling double with (21,)
42
calling deposit with (50,)
Account.deposit() missing 1 required positional argument: 'amount'

Binding the decorator to the instance

To work on methods, the decorator class must define __get__. Python calls this method when the attribute is looked up, and it can return a bound method.

method_fixed.py
import functools
import types


class Trace:

    def __init__(self, func):
        functools.update_wrapper(self, func)
        self.func = func

    def __call__(self, *args, **kwargs):
        print(f"calling {self.func.__name__} with {args[1:]}")
        return self.func(*args, **kwargs)

    def __get__(self, instance, owner):
        if instance is None:
            return self
        return types.MethodType(self, instance)


class Account:

    def __init__(self, balance):
        self.balance = balance

    @Trace
    def deposit(self, amount):
        self.balance += amount

    @Trace
    def withdraw(self, amount):
        self.balance -= amount


acc = Account(100)
acc.deposit(50)
acc.withdraw(30)
print(acc.balance)

print(type(Account.deposit).__name__, type(acc.deposit).__name__)

When acc.deposit is looked up, Python calls Trace.__get__ with the account as instance. types.MethodType(self, instance) creates a bound method that calls the Trace object with the account as the first argument, exactly as with a plain function. Accessed on the class, instance is None and the decorator returns itself. The __get__ method is part of the descriptor protocol, described in Python __get__ method.

$ python method_fixed.py
calling deposit with (50,)
calling withdraw with (30,)
120
Trace method

Composing callables

A callable object can hold other callables and call them in turn. The result is again a callable, so the combination can be nested and passed on like any other function.

pipeline.py
class Replace:

    def __init__(self, old, new):
        self.old = old
        self.new = new

    def __call__(self, text):
        return text.replace(self.old, self.new)


class Pipeline:

    def __init__(self, *steps):
        self.steps = steps

    def __call__(self, value):
        for step in self.steps:
            value = step(value)
        return value

    def then(self, *steps):
        return Pipeline(*self.steps, *steps)


slug = Pipeline(str.strip, str.lower, Replace(" ", "-"))
short_slug = slug.then(lambda s: s[:12], Replace("--", "-"))

titles = ["  Hello there ", "Python Callable Objects", "A  B"]

for title in titles:
    print(f"{slug(title)!r:30} {short_slug(title)!r}")

nested = Pipeline(slug, str.upper)
print(nested(" Two Steps "))

A Pipeline passes a value through its steps, which can be built-in methods such as str.strip, lambdas, or callable objects such as Replace. The then method returns a new, longer pipeline and leaves the original unchanged. Since a pipeline is itself callable, it can be a step of another pipeline, as in nested.

$ python pipeline.py
'hello-there'                  'hello-there'
'python-callable-objects'      'python-calla'
'a--b'                         'a-b'
TWO-STEPS

Source

Data model: __call__, Data model: __get__, types.MethodType, Descriptor guide: functions and methods

In this article we have used callable objects as configurable functions, given them extra methods, mixed them with other callbacks, written a decorator class with arguments, made a decorator class work on methods with __get__, and composed callables into pipelines. When there is no state or configuration, a plain function remains the simpler choice. See also Python __call__ method, Python closures, and Python object creation.

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.