Composition and inheritance solve different design problems in Python. Inheritance says an object is a more specific kind of another object and can honor a compatible interface. Composition says an object performs part of its work by using another object with a narrower responsibility. Both are useful, but they should be chosen from the contracts the application needs rather than a slogan that one technique is always superior. The distinction becomes clear when an application sends notifications, records outcomes and supports more than one delivery mechanism.
A good design exercise begins with expected behavior. The application must validate a message, deliver it through an approved channel, and report whether delivery was attempted. The channel may be replaced for testing or because a service provider changes. The validation rule might be shared by different notification types. Those requirements suggest one composed dependency for delivery and, perhaps, inheritance for a legitimate variant that preserves the notification contract. The goal is a testable boundary, not a deep family tree.
Composition expresses a dependency explicitly
Consider a notification service that sends messages through a delivery object supplied when the service is constructed. Its client does not need to know the details of email, SMS or a test double. It needs a small contract: the delivery object provides a send method that accepts a message and returns a result. The service can validate input before delegating. This relationship is ‘has a sender’ rather than ‘is a sender.’
class MemorySender:
def __init__(self):
self.sent = []
def send(self, message):
self.sent.append(message)
return True
class NoticeService:
def __init__(self, sender):
self.sender = sender
def dispatch(self, message):
if not message.strip():
raise ValueError('A message is required')
return self.sender.send(message)
sender = MemorySender()
service = NoticeService(sender)
assert service.dispatch('Maintenance at 18:00') is True
assert sender.sent == ['Maintenance at 18:00']
This small example can be executed with Python’s standard library alone. It demonstrates an important limit: the sample sender only stores a message in memory; it is not a secure or functioning production message transport. A real sender would need credentials, timeouts, retry policy, audit requirements and controls for private data. The composition boundary makes those responsibilities replaceable without teaching the higher-level service about network-specific configuration.
Dependency injection can also make unit tests faster and less fragile. A test can pass a deliberately failing sender to check that the service handles the failure appropriately. It should not need to contact an external mail server every time validation logic changes. That does not eliminate integration tests: the real transport still needs separate tests in an approved nonproduction environment. The technique separates concerns; it does not prove the external system is correct.
Inheritance is appropriate when the subtype preserves the contract
Suppose a specialized notification must add an audit event after successful dispatch. A subclass may extend the existing behavior if it remains a valid NoticeService: callers should still be able to pass a message and receive the same kind of return result. The override should respect documented errors and should not weaken validation. super() can invoke behavior from the next class in Python’s method resolution order instead of copying the parent implementation.
class AuditedNoticeService(NoticeService):
def __init__(self, sender, audit):
super().__init__(sender)
self.audit = audit
def dispatch(self, message):
result = super().dispatch(message)
if result:
self.audit.append(('sent', message))
return result
audit = []
tracked = AuditedNoticeService(sender, audit)
assert tracked.dispatch('Service restored') is True
assert audit == [('sent', 'Service restored')]
The example demonstrates one behavioral extension, but it also exposes a design concern. The audit record currently stores the full message; production systems should avoid leaking personal or sensitive content into logs. It may be better to store a safe event identifier and status instead. The subclass must also define what happens if audit recording fails after delivery. In a real application, that is a business consistency decision, not a detail that inheritance resolves automatically.
Inheritance creates coupling to the parent class’s methods, initialization and extension points. If the base service changes dispatch, a subclass override may unexpectedly change behavior. Use a subclass when the relationship is a stable and meaningful subtype, not just because two unrelated classes share five lines of code. Often a composed validator, transport or audit dependency is easier to replace and test than an expanding collection of special-purpose subclasses.
Python method lookup is a defined algorithm
Python resolves attributes through the class and its bases according to the method resolution order, commonly exposed as Class.__mro__ or Class.mro(). With straightforward single inheritance this usually seems intuitive. With multiple inheritance, the order is not just a naive left-to-right recursive search: Python uses a consistent linearization that preserves local base ordering and cooperative method calls. The official Python class tutorial explains these rules and why the order must be monotonic.
A minimal demonstration makes the behavior visible without metaphors:
class Base:
def label(self):
return 'base'
class Left(Base):
def label(self):
return 'left > ' + super().label()
class Right(Base):
def label(self):
return 'right > ' + super().label()
class Combined(Left, Right):
pass
assert Combined().label() == 'left > right > base'
assert Combined.__mro__[:4] == (Combined, Left, Right, Base)
super() does not always mean ‘call the textually named parent.’ It continues resolution from a particular point in the MRO. In cooperative multiple inheritance, every participating class needs compatible method signatures and consistent calls to super(). A mixin that silently omits the next method can break the chain. It is a reason to keep mixins narrow and documented, and to favor composition when the behavior does not represent a stable hierarchy.
Class attributes and instance attributes are separate decisions
Inheritance questions often become confused with shared class state. A class attribute is accessible through instances and may be shared across them until an instance shadows it; a mutable class attribute can unintentionally accumulate data from many instances. Assigning a new list inside __init__ creates an instance-specific value. If a subclass inherits a mutable class attribute, it can contribute to the same shared object unless it explicitly defines its own storage.
The deeper distinction between class and instance state is discussed in the site’s treatment of Python object-oriented programming. For this article, the design decision is narrower: a sender’s sent history belongs to the sender instance, and each notice service receives that object explicitly. Two services intentionally sharing one sender can observe the same history, while two different sender instances have separate lists. The behavior follows object ownership rather than a class-level global list.
A useful test creates two MemorySender instances and verifies that dispatching through the first does not alter the second. Add a test that passes an empty string and expects ValueError. These assertions protect the composition contract from a future refactor that accidentally shares mutable state. They also show why a design should be evaluated through behavior and state ownership rather than through its number of classes.
Protocols and abstract base classes offer contract options
Python supports structural typing with typing.Protocol, which can express that an object supplies a required method without forcing it to inherit a particular base class. This is often a good fit for a pluggable sender. Static type checkers can flag an incompatible implementation, but the annotation alone does not turn arbitrary runtime objects into safe dependencies or validate untrusted input.
An abstract base class can provide a nominal contract and prevent direct instantiation when abstract methods are unimplemented. It may be appropriate for a framework with a stable extension API. Choose it because runtime relationship and shared implementation are useful, not because every dependency needs a formal class hierarchy. The notification example works with a simple injected object precisely because the behavioral contract is small and easy to test.
In practice, dependency injection, protocols and inheritance can coexist. The service could accept an object satisfying a Sender protocol; specialized services might use inheritance for a carefully specified extension; concrete transport objects can be composed from smaller retry and authentication helpers. The design remains healthy only if those layers make failure and ownership easier to understand. Excessive abstraction can make a ten-line feature difficult to debug.
Decide using failure modes and change pressure
Ask three questions when choosing between composition and inheritance. What must remain substitutable? Which behavior changes independently? Where does state live when an operation fails? If delivery providers change frequently, composition keeps that volatile choice behind an interface. If several kinds of notices must satisfy one stable service contract, a small amount of inheritance may help. If no natural ‘is a’ relationship exists, inheritance is probably adding more coupling than value.
Test both success and partial failure. A sender may time out after receiving a request; blindly retrying can send duplicate notifications. An audit operation may fail after dispatch succeeds. A subclass can preserve the return type yet violate a business invariant if it changes retry or audit semantics. Model those constraints explicitly with status identifiers and idempotency support where appropriate. No class structure can compensate for unclear delivery guarantees.
For maintainability, prefer readable methods and transparent dependencies over deep hierarchies. Record why the design was chosen and the cases it deliberately excludes. A future engineer should be able to replace a delivery channel, inspect a failing test and explain what super() will call without guessing. Composition and inheritance are valuable Python mechanisms when they make those responsibilities explicit; they are liabilities when they hide who performs the work or owns the state.