Sub topic 13
When to Prefer Composition
This chapter assumes you can write classes, override methods, call super(), and read a method resolution order (MRO). It builds on the earlier chapters on substitutability and mixins. Here you learn to decide when a class should extend another class and when it should hold another object instead.
Is-a versus has-a
Inheritance models an is-a relationship. A Dog is an Animal, so code that accepts an Animal can accept a Dog. Composition models a has-a relationship. A Car has an Engine, so the car stores an engine object in an attribute and calls its methods.
Both approaches reuse code. They differ in what they promise to callers and how tightly they bind two classes.
| Question | Inheritance | Composition |
|---|---|---|
| Public interface | Everything the parent exposes | Only what you write |
| Coupling | To the parent's internals | To the part's public methods |
| When the relationship is fixed | At class definition | At construction, or later by reassignment |
| Reuse of several behaviors | Multiple inheritance and MRO | Several attributes |
| Typical check | `isinstance(x, Parent)` | Method calls on the part |
Problem 1: the subclass inherits too much
A subclass exposes every public method of its parent. If the parent is a general-purpose type, the subclass gains operations that break its own rules.
class Stack(list):
def push(self, item):
self.append(item)
def pop_top(self):
return self.pop()
s = Stack()
s.push(1)
s.push(2)
s.insert(0, 99) # a stack should not allow this
print(s) # [99, 1, 2]Stack is a list by inheritance, so callers can insert in the middle, sort, or reverse it. You cannot remove those methods without breaking the is-a promise. Composition lets you expose only the operations you want.
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
return self._items.pop()
def __len__(self):
return len(self._items)
s = Stack()
s.push(1)
s.push(2)
print(s.pop(), len(s)) # 2 1
try:
s.insert(0, 99)
except AttributeError as exc:
print("AttributeError:", exc) # 'Stack' object has no attribute 'insert'The list is now an implementation detail. You could switch to collections.deque later without changing any caller.
Problem 2: the subclass depends on the parent's internals
A subclass is coupled to how the parent's methods call each other, not only to what they return. This is sometimes called the fragile base class problem. Here a subclass tries to count added items.
class Bag:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
def add_all(self, items):
for item in items:
self.add(item)
class CountingBag(Bag):
def __init__(self):
super().__init__()
self.added = 0
def add(self, item):
self.added += 1
super().add(item)
def add_all(self, items):
self.added += len(items)
super().add_all(items)
bag = CountingBag()
bag.add_all(["a", "b", "c"])
print(bag.added) # 6, not 3Bag.add_all calls self.add, and self is a CountingBag, so every item is counted twice. If you remove the override of add_all, the count is right. But if the parent's author later changes add_all to call self.items.extend(items), the count is wrong again. The subclass is correct only while the parent keeps its current internal structure.
A composed version depends only on the public add method of the part it wraps.
class Bag:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
def add_all(self, items):
for item in items:
self.add(item)
class CountingBag:
def __init__(self):
self._bag = Bag()
self.added = 0
def add(self, item):
self.added += 1
self._bag.add(item)
def add_all(self, items):
for item in items:
self.add(item)
bag = CountingBag()
bag.add_all(["a", "b", "c"])
print(bag.added) # 3The wrapper decides for itself how add_all works. The inner Bag calls its own add, which is the plain Bag.add, so nothing is counted twice.
Problem 3: built-in types skip your overrides
In CPython, the built-in containers implement many methods in C and do not route them through your overridden methods. Subclassing dict and overriding __setitem__ only catches item assignment with square brackets.
class LoudDict(dict):
def __setitem__(self, key, value):
print(f"set {key}")
super().__setitem__(key, value)
d = LoudDict()
d["a"] = 1 # prints: set a
d.update(b=2) # prints nothing
print(d) # {'a': 1, 'b': 2}The update call stored a value without running your hook. The same happens with setdefault and with passing keyword arguments to the constructor.
The standard library provides UserDict, UserList, and UserString for this case. They wrap a regular container in a data attribute, which is composition. Their other methods are written in terms of the methods you override.
from collections import UserDict
class LoudDict(UserDict):
def __setitem__(self, key, value):
print(f"set {key}")
super().__setitem__(key, value)
d = LoudDict()
d["a"] = 1
d.update(b=2)
print(d) # {'a': 1, 'b': 2}This prints set a and set b before the dictionary. If you need a mapping with custom behavior, start from UserDict or collections.abc.MutableMapping, not from dict.
Problem 4: behaviors multiply into subclasses
Suppose an alert can go out by email or SMS, and its text can be plain or urgent. With inheritance you need a subclass for each combination: EmailAlert, SmsAlert, UrgentEmailAlert, UrgentSmsAlert. Each new channel or style doubles the count.
With composition, each varying behavior becomes an object passed to the constructor.
class EmailSender:
def send(self, text):
print(f"email: {text}")
class SmsSender:
def send(self, text):
print(f"sms: {text}")
class Alert:
def __init__(self, sender, prefix="ALERT"):
self.sender = sender
self.prefix = prefix
def fire(self, message):
self.sender.send(f"{self.prefix}: {message}")
alert = Alert(EmailSender())
alert.fire("disk full") # email: ALERT: disk full
alert.sender = SmsSender() # swap the behavior at run time
alert.fire("disk full") # sms: ALERT: disk full
urgent = Alert(SmsSender(), prefix="URGENT")
urgent.fire("disk full") # sms: URGENT: disk fullAlert does not know which sender it has. Any object with a send(text) method works. This is polymorphism applied to the parts instead of to the main class. The relationship can also change while the program runs, which a class hierarchy cannot do.
Delegation and its cost
When the wrapper must expose many of the part's methods unchanged, you write forwarding methods. Each forwarder is boilerplate, and that is the main cost of composition.
class Engine:
def start(self):
return "engine started"
def stop(self):
return "engine stopped"
class Car:
def __init__(self, engine):
self._engine = engine
def start(self):
return self._engine.start()
def stop(self):
return self._engine.stop()
car = Car(Engine())
print(car.start()) # engine startedYou can reduce forwarding with __getattr__, which Python calls only when normal lookup fails. This is shorter but hides the public interface from readers, editors, and type checkers. Use it for thin proxies, not for ordinary classes.
Common errors
- Subclassing to borrow one method. If
ReportextendsDatabaseonly to callself.query(), a report is not a database. Store aDatabaseinstead. - Using inheritance for a role that changes. An
Employeewho becomes aManagercannot change class. Give the employee aroleobject. - Deep hierarchies. Past two or three levels, readers must hold the whole MRO in mind to know which method runs.
- Inheriting from a class you do not control. Its internals can change in a new release, and your subclass breaks.
- Making a wrapper that only forwards. If it adds no behavior, callers can use the part directly.
Choosing between them
Use inheritance when all of these hold:
- The subclass is truly a specialized kind of the parent.
- Callers can use the subclass anywhere the parent is accepted.
- You control the parent, or it is documented as a base class for extension.
- You want the subclass to inherit the whole public interface.
Otherwise, prefer composition. A common combined design uses both: an abstract base class defines the interface of the parts, and the main class holds a part that implements it.
Exercise
A teammate writes class Cache(dict) and overrides __setitem__ to record the time each key was stored. Later you find some keys have no timestamp. What is the likely cause, and how do you fix the design?
Show answer
Keys were added through update(), setdefault(), or the constructor, which on a dict subclass do not call the overridden __setitem__. Fix it by composing instead: derive from collections.UserDict (which wraps a dict in self.data and routes update through __setitem__), or write a class that holds a dict and exposes only the methods you control.
Exercise
A Notifier class has three delivery channels (email, SMS, push) and two formats (short, long). Describe how to design it with composition and say how many classes you need for the channels and formats combined.
Show answer
Make one class per channel with a send(text) method (3 classes) and one class per format with a render(message) method (2 classes), then have Notifier.__init__ accept a sender and a formatter. That is 5 small classes plus Notifier, instead of 6 subclasses. Adding a fourth channel adds one class, not two.