Sub topic 13
Composition or inheritance: choosing a design
Inheritance and composition are two ways to reuse code. Inheritance says a new class is a kind of an existing class. Composition says a new class has another object and uses it. This chapter gives you criteria for choosing between them and shows what goes wrong when you choose badly.
This chapter assumes you can write classes with __init__, define methods, and subclass with super(). It also assumes you know what duck typing is, meaning an object is used by what it can do, not by what it inherits from.
Two relationships, two designs
The question to ask is which sentence is true:
- A
Dogis anAnimal. This points to inheritance. - A
Carhas anEngine. This points to composition.
Composition means a class stores other objects in its attributes and delegates work to them.
class Engine:
def start(self):
return "engine started"
class Car:
def __init__(self):
self.engine = Engine() # Car has an Engine
def start(self):
return self.engine.start()
print(Car().start()) # engine startedCar is not a subclass of Engine. A car is not an engine, and Car should not accept every operation an engine accepts. It exposes only the methods you write on it.
What inheritance costs
Subclassing is the tightest coupling Python offers. A subclass depends on three things in its parent:
- Its public methods.
- Its internal behavior, such as which methods call which.
- Its future changes, because anything the parent adds is inherited automatically.
The costs show up in several ways:
- Leaked interface. The subclass exposes everything the parent has, including methods that break your class's rules.
- Fragile base class. If the parent changes how its methods call each other, subclasses that override them can break.
- Class explosion. Each independent variation needs its own subclass. Two engine types and two transmission types need four subclasses.
- Fixed at definition time. An object cannot change its parent class while the program runs.
Leaked interface: a stack that is a list
Subclassing list to build a stack looks like a shortcut:
class BadStack(list):
def push(self, item):
self.append(item)
s = BadStack()
s.push(1)
s.push(2)
s.insert(0, 99) # still allowed: a stack should never do this
print(s) # [99, 1, 2]A stack promises last-in, first-out order, but insert, sort, reverse, and slicing are all still available. Composition exposes only what you choose:
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)
def __repr__(self):
return f"Stack({self._items!r})"
s = Stack()
s.push(1)
s.push(2)
print(s.pop()) # 2
print(s) # Stack([1])
print(len(s)) # 1The leading underscore on _items signals that callers should not touch the list. If you later store items in a collections.deque instead, no caller is affected.
Swapping parts at runtime
Composition lets you replace a part without creating a new class. Pass the part in through __init__, which is often called dependency injection.
class GasEngine:
def start(self):
return "gas engine started"
class ElectricMotor:
def start(self):
return "electric motor humming"
class Car:
def __init__(self, engine):
self.engine = engine
def start(self):
return self.engine.start()
car = Car(GasEngine())
print(car.start()) # gas engine started
car.engine = ElectricMotor() # swap the part on a live object
print(car.start()) # electric motor hummingCar does not check the type of engine. Any object with a start() method works. This is duck typing doing the job that a shared base class would do in other languages.
The inheritance version needs GasCar and ElectricCar. Add a second axis such as transmission and you need GasManualCar, GasAutoCar, ElectricManualCar, and ElectricAutoCar. With composition, you pass in one engine and one transmission, and you write each part once. Testing is also easier, because you can pass in a fake engine that records calls.
Delegation
When your class wraps another object and forwards calls to it, this is called delegation. Writing each forwarding method by hand is tedious, so Python offers __getattr__. It runs only when normal attribute lookup fails.
class Logged:
def __init__(self, wrapped):
self._wrapped = wrapped
def __getattr__(self, name):
attr = getattr(self._wrapped, name)
if callable(attr):
def wrapper(*args, **kwargs):
print(f"calling {name}")
return attr(*args, **kwargs)
return wrapper
return attr
data = Logged([3, 1, 2])
data.append(4) # calling append
data.sort() # calling sort
print(data._wrapped) # [1, 2, 3, 4]_wrapped is found by normal lookup, so __getattr__ never handles it. This matters for the gotcha below.
Delegation through __getattr__ has limits:
- Special methods such as
__len__or__iter__are looked up on the class, not the instance, so__getattr__does not forward them.len(data)fails here. You must define those methods explicitly. - It makes the wrapper's interface implicit, so editors and readers cannot see what it supports. Use it for thin wrappers. For a real domain class, write the forwarding methods you want.
When inheritance is the right tool
Inheritance is not wrong, and it is the better design in these cases:
- A true is-a relationship holds. Every
Squarereally can be used wherever aShapeis expected. Code that works with the parent must keep working with the subclass. This is the Liskov substitution principle. - You are extending a class designed for it. Examples are
Exception,abc.ABCinterfaces, and framework base classes that document subclassing as the extension point. - You want to share a small amount of stable behavior and the parent is under your control.
- You need
isinstancechecks to reflect the type hierarchy.
Even with a true is-a relationship, a bad hierarchy appears when subclasses must disable inherited behavior. A subclass method that raises NotImplementedError to turn off a parent method shows that the hierarchy is wrong. A class named Penguin(Bird) where fly() raises an error is the classic case.
Combining the two
Real designs mix both. A common pattern is a small abstract base class that defines the interface, plus concrete classes that are composed into a larger object.
from abc import ABC, abstractmethod
class Notifier(ABC):
@abstractmethod
def send(self, message):
...
class EmailNotifier(Notifier):
def send(self, message):
return f"email: {message}"
class SmsNotifier(Notifier):
def send(self, message):
return f"sms: {message}"
class OrderService:
def __init__(self, notifier):
self.notifier = notifier # composed, typed by the interface
def place_order(self, order_id):
return self.notifier.send(f"order {order_id} placed")
print(OrderService(EmailNotifier()).place_order(7)) # email: order 7 placed
print(OrderService(SmsNotifier()).place_order(7)) # sms: order 7 placedThe hierarchy is shallow, with one interface and its implementations. OrderService does not inherit from any notifier. It holds one.
Decision guide
| Question | Favors inheritance | Favors composition |
|---|---|---|
| Relationship | is-a | has-a, uses-a |
| Coupling | Tight, shares internals | Loose, only the public interface |
| Interface exposed | Everything the parent has | Only what you write |
| Changing behavior at runtime | Not possible | Replace the part |
| Variations on several axes | Many subclasses | Combine small parts |
| Framework extension point | Often required | Rarely |
If you are unsure, start with composition. It is easier to change to inheritance later than the reverse, because moving from inheritance to composition changes the public interface that callers depend on.
Exercises
Exercise
A teammate writes class Inventory(dict) and adds an add_item(name, qty) method. Callers can still run inventory.clear() or inventory["x"] = -5. Which design change fixes this, and what do you give up?
Show answer
Make Inventory hold a private dict (self._stock = {}) and expose only methods such as add_item and remove_item, with validation for quantities. Composition hides the unwanted dict methods and lets you change the storage later. You give up inherited conveniences. You must write forwarding methods such as __len__, __getitem__, or __iter__ yourself for the operations you want to keep.
Exercise
Why does len(Logged([1, 2, 3])) raise a TypeError even though Logged defines __getattr__ that forwards to the list?
Show answer
Python looks up special methods such as __len__ on the type of the object, not on the instance, and it does not go through __getattr__ for that lookup. Logged has no __len__ of its own, so len() fails. Define __len__ explicitly on the wrapper and have it return len(self._wrapped).