Composition and delegation

suggest change

Composition means building an object out of other objects: a Car has an Engine, a Cart has a discount policy. Delegation means that the outer object forwards some of its work to the inner object instead of doing it itself.

Inheritance models an is a relationship and gives you every method of the parent, whether you want it or not. Composition models has a and gives you only what you choose to expose. The common advice "favor composition over inheritance" comes from this: composed objects are easier to change, test and reason about.

See Basic inheritance and Class composition for the basics. This article covers the practical techniques: explicit forwarding, __getattr__ proxies and their pitfalls, building on collections.abc, delegating descriptors and the strategy pattern.

Why not just inherit?

Subclassing built-in types looks like the quickest way to customize them, but it often doesn't work the way you'd expect. Here's a dict that should lowercase every key:

class LowerDict(dict):
    def __setitem__(self, key, value):
        super().__setitem__(key.lower(), value)

d = LowerDict({"Name": "Alice"})
d["City"] = "Paris"
d.update({"Country": "France"})
print(d)
{'Name': 'Alice', 'city': 'Paris', 'Country': 'France'}

Only d["City"] = ... went through our __setitem__. The C implementations of dict.__init__ and dict.update (and setdefault, |=, ...) write to the dict directly and never call the overridden method. To get this right through inheritance you would have to override every method that can insert a key.

There are other problems with inheritance:

We'll fix LowerDict with composition later in this article.

Basic composition

Store the part as an attribute and use it:

class Engine:
    def __init__(self, horsepower: int):
        self.horsepower = horsepower
        self.running = False

    def start(self) -> None:
        self.running = True

    def stop(self) -> None:
        self.running = False


class Car:
    def __init__(self, model: str, engine: Engine):
        self.model = model
        self.engine = engine          # Car HAS an Engine

    def drive(self) -> str:
        if not self.engine.running:
            self.engine.start()
        return f"{self.model} driving with {self.engine.horsepower} hp"


car = Car("Roadster", Engine(300))
print(car.drive())
print(car.engine.running)

car.engine = Engine(450)   # swap the part at runtime
print(car.drive())
Roadster driving with 300 hp
True
Roadster driving with 450 hp

Car receives its Engine from outside rather than creating it. That makes it trivial to pass a fake engine in tests. This is dependency injection, and it goes hand in hand with composition.

Explicit delegation: forwarding methods

The simplest form of delegation is writing a method that calls the same method on the inner object. It's verbose, but it's explicit, readable and works with every tool (IDEs, type checkers, help()).

A stack built on a list exposes only stack operations:

class Stack:
    def __init__(self):
        self._items = []

    def push(self, item):
        self._items.append(item)

    def pop(self):
        return self._items.pop()

    def peek(self):
        return self._items[-1]

    def __len__(self):
        return len(self._items)

    def __bool__(self):
        return bool(self._items)


s = Stack()
s.push(1)
s.push(2)
print(s.pop(), len(s), bool(s))
print(hasattr(s, "insert"))
2 1 True
False

Unlike class Stack(list), nobody can call s.insert(0, x) or s.sort() and break the last-in, first-out order. The leading underscore on _items signals that the list is an implementation detail (see Visibility and encapsulation).

Prefer explicit forwarding when you expose a handful of methods. Reach for the automatic techniques below only when you need to forward many methods or don't know them in advance.

Automatic delegation with __getattr__

Python calls __getattr__(self, name) only when normal attribute lookup fails, i.e. when name isn't found on the instance or its class. That makes it a natural hook for forwarding "everything else" to a wrapped object.

Here's a wrapper that times every method call of any object:

import time


class Timed:
    """Wraps any object and logs how long each method call takes."""

    def __init__(self, wrapped):
        self._wrapped = wrapped

    def __getattr__(self, name):
        attr = getattr(self._wrapped, name)
        if not callable(attr):
            return attr

        def wrapper(*args, **kwargs):
            start = time.perf_counter()
            try:
                return attr(*args, **kwargs)
            finally:
                elapsed = (time.perf_counter() - start) * 1000
                print(f"{name} took {elapsed:.2f} ms")

        return wrapper


items = Timed([5, 3, 8, 1])
items.append(4)
items.sort()
print(items.index(8))
print(items._wrapped)
append took 0.00 ms
sort took 0.00 ms
index took 0.00 ms
4
[1, 3, 4, 5, 8]

items._wrapped is found by normal lookup, so __getattr__ isn't involved. append, sort and index aren't defined on Timed, so they go through __getattr__ and get wrapped.

The same pattern is used for logging, caching, access control, lazy loading and adding a few methods to an object you don't control (for example, a third-party client).

Pitfall: special methods bypass __getattr__

Implicit special method lookups such as len(x), x[0], x + y, iter(x) or with x: look up the dunder method on the type, not the instance. They never go through __getattr__:

class Proxy:
    def __init__(self, wrapped):
        self._wrapped = wrapped

    def __getattr__(self, name):
        return getattr(self._wrapped, name)


p = Proxy([1, 2, 3])
print(p.count(2))
print(p.__len__())
try:
    print(len(p))
except TypeError as e:
    print("TypeError:", e)
try:
    print(p[0])
except TypeError as e:
    print("TypeError:", e)
1
3
TypeError: object of type 'Proxy' has no len()
TypeError: 'Proxy' object is not subscriptable

Calling p.__len__() explicitly works because that's an ordinary attribute lookup, but len(p) doesn't. If your proxy should behave like a container, number or context manager, you must define those dunder methods on the class yourself.

Pitfall: infinite recursion

__getattr__ can be called before __init__ has run. copy.copy(), pickle and some frameworks create an instance without calling __init__ and then probe it for methods like __setstate__ or __reduce_ex__. Inside __getattr__, self._wrapped doesn't exist yet, so accessing it calls __getattr__("_wrapped") again, forever:

import copy
import pickle


class BadProxy:
    def __init__(self, wrapped):
        self._wrapped = wrapped

    def __getattr__(self, name):
        return getattr(self._wrapped, name)


class GoodProxy:
    def __init__(self, wrapped):
        self._wrapped = wrapped

    def __getattr__(self, name):
        if name.startswith("__") or name == "_wrapped":
            raise AttributeError(name)
        return getattr(self._wrapped, name)


try:
    copy.copy(BadProxy([1, 2]))
except RecursionError as e:
    print("RecursionError:", e)

c = copy.copy(GoodProxy([1, 2]))
print(c.count(1))
print(pickle.loads(pickle.dumps(GoodProxy([1, 2])))._wrapped)
RecursionError: maximum recursion depth exceeded
1
[1, 2]

Two rules keep __getattr__ proxies safe:

__getattr__ must raise AttributeError (not KeyError or anything else) for missing attributes, otherwise hasattr() and getattr(obj, name, default) break.

Combining explicit dunders with selective forwarding

A robust proxy usually defines the dunders it needs, forwards an explicit allow-list of ordinary methods and implements __dir__ so that tab completion and dir() show the forwarded names:

class ReadOnlyList:
    """A read-only view over a list."""

    _allowed = {"count", "index", "copy"}

    def __init__(self, data: list):
        self._data = data

    # dunders must be forwarded explicitly
    def __len__(self):
        return len(self._data)

    def __getitem__(self, index):
        return self._data[index]

    def __iter__(self):
        return iter(self._data)

    def __contains__(self, item):
        return item in self._data

    def __repr__(self):
        return f"ReadOnlyList({self._data!r})"

    # ordinary methods: forward only an allow-list
    def __getattr__(self, name):
        if name in self._allowed:
            return getattr(self._data, name)
        raise AttributeError(f"{type(self).__name__!r} object has no attribute {name!r}")

    def __dir__(self):
        return sorted(set(super().__dir__()) | self._allowed)


src = [3, 1, 4, 1, 5]
view = ReadOnlyList(src)
print(len(view), view[0], view[-2:], 4 in view)
print(view.count(1), sorted(view))
src.append(9)
print(view)
try:
    view.append(2)
except AttributeError as e:
    print("AttributeError:", e)
print("count" in dir(view), "append" in dir(view))
5 3 [1, 5] True
2 [1, 1, 3, 4, 5]
ReadOnlyList([3, 1, 4, 1, 5, 9])
AttributeError: 'ReadOnlyList' object has no attribute 'append'
True False

The view reflects changes to the underlying list (9 shows up) but offers no way to modify it. types.MappingProxyType in the standard library is the same idea for dicts.

Composition plus collections.abc

Wrapping a container means forwarding many methods. The abstract base classes in collections.abc remove most of that work: implement a few core methods and the mixin methods (get, update, setdefault, pop, keys, items, __contains__, __eq__, ...) are provided for you, built on top of your core methods.

Here's LowerDict done right. It has a dict instead of being one:

from collections.abc import MutableMapping


class LowerDict(MutableMapping):
    def __init__(self, *args, **kwargs):
        self._data = {}
        self.update(*args, **kwargs)   # update() comes from MutableMapping

    def __getitem__(self, key):
        return self._data[key.lower()]

    def __setitem__(self, key, value):
        self._data[key.lower()] = value

    def __delitem__(self, key):
        del self._data[key.lower()]

    def __iter__(self):
        return iter(self._data)

    def __len__(self):
        return len(self._data)

    def __repr__(self):
        return f"{type(self).__name__}({self._data!r})"


d = LowerDict({"Name": "Alice"}, Age=30)
d["City"] = "Paris"
d.update({"Country": "France"})
d.setdefault("ZIP", "75001")
print(d)
print(d["NAME"], "city" in d, d.get("missing", "-"))
print(isinstance(d, MutableMapping), isinstance(d, dict))
LowerDict({'name': 'Alice', 'age': 30, 'city': 'Paris', 'country': 'France', 'zip': '75001'})
Alice True -
True False

Every insertion path (__init__, update, setdefault) now goes through our __setitem__, and lookups such as d["NAME"] and "city" in d go through __getitem__. Five small methods give a complete, consistent mapping.

The same approach works with Sequence, MutableSequence, Set and MutableSet. collections.UserDict, UserList and UserString are ready-made wrappers that store the data in self.data and also route all operations through the overridable methods.

Delegating attributes with a descriptor

When you want to expose a few specific attributes of a component as if they belonged to the outer object, a small descriptor avoids writing a property for each one:

class Delegate:
    """Descriptor that forwards attribute access to self.<to>.<name>."""

    def __init__(self, to: str):
        self.to = to

    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return getattr(getattr(obj, self.to), self.name)

    def __set__(self, obj, value):
        setattr(getattr(obj, self.to), self.name, value)


class Address:
    def __init__(self, street: str, city: str):
        self.street = street
        self.city = city

    def format(self) -> str:
        return f"{self.street}, {self.city}"


class Customer:
    city = Delegate("address")
    format = Delegate("address")

    def __init__(self, name: str, address: Address):
        self.name = name
        self.address = address


c = Customer("Bob", Address("1 Main St", "Springfield"))
print(c.city)
print(c.format())
c.city = "Shelbyville"
print(c.address.city)
print([n for n in vars(Customer) if not n.startswith("_")])
Springfield
1 Main St, Springfield
Shelbyville
['city', 'format']

__set_name__ (Python 3.6+) tells each Delegate the name it was assigned to, so city = Delegate("address") forwards to self.address.city. Unlike __getattr__, the delegated names are visible on the class, show up in dir() and are found by normal lookup, so there's no recursion risk.

The strategy pattern: composing behavior

Composition isn't only about data. You can plug in behavior by giving an object a component that implements an algorithm. Swapping the component changes the behavior without subclassing.

typing.Protocol describes what the component must look like. Any class with a matching apply method qualifies; no common base class is needed:

from dataclasses import dataclass, field
from typing import Protocol


class Discount(Protocol):
    def apply(self, total: float) -> float: ...


class NoDiscount:
    def apply(self, total: float) -> float:
        return total


@dataclass
class PercentOff:
    percent: float

    def apply(self, total: float) -> float:
        return total * (1 - self.percent / 100)


@dataclass
class AmountOff:
    amount: float
    minimum: float = 0.0

    def apply(self, total: float) -> float:
        return total - self.amount if total >= self.minimum else total


@dataclass
class Cart:
    discount: Discount = field(default_factory=NoDiscount)
    items: list[tuple[str, float]] = field(default_factory=list)

    def add(self, name: str, price: float) -> None:
        self.items.append((name, price))

    def total(self) -> float:
        subtotal = sum(price for _, price in self.items)
        return round(self.discount.apply(subtotal), 2)


cart = Cart()
cart.add("book", 30.0)
cart.add("pen", 5.0)
print(cart.total())

cart.discount = PercentOff(10)
print(cart.total())

cart.discount = AmountOff(10, minimum=50)
print(cart.total())
print(cart)
35.0
31.5
35.0
Cart(discount=AmountOff(amount=10, minimum=50), items=[('book', 30.0), ('pen', 5.0)])

With inheritance you'd need PercentOffCart, AmountOffCart and so on, and combining them with another axis of variation (say, shipping rules) multiplies the number of subclasses. With composition, each axis is an independent component.

In Python, a strategy with a single method is often just a function:

from typing import Callable

Pricing = Callable[[float], float]


def black_friday(total: float) -> float:
    return total * 0.7


class Cart:
    def __init__(self, pricing: Pricing = lambda t: t):
        self.pricing = pricing
        self.prices: list[float] = []

    def total(self) -> float:
        return self.pricing(sum(self.prices))


cart = Cart(black_friday)
cart.prices += [10, 20]
print(cart.total())
21.0

Composition vs. inheritance vs. mixins

Use When
Inheritance there's a true is a relationship, the subclass honors the whole parent interface, and you control both classes (or the parent is designed to be subclassed, e.g. an ABC)
Mixins you want to add a small, self-contained capability (e.g. __repr__, JSON serialization) to many unrelated classes
Composition the relationship is has a or uses a, you want to expose only part of a component's interface, or you need to swap the component at runtime or in tests

Guidelines:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents