Sub topic 12
Overriding without breaking callers
This chapter assumes you can write subclasses, override methods, and call super(). It covers how to override a method so that code written for the parent class keeps working with the subclass.
The substitution rule
Overriding changes behavior, and some of that code is not yours. A function that accepts an Animal may receive a Dog it has never seen. The Liskov substitution principle describes when that is safe: anywhere a parent object works, a subclass object must work too, without the caller knowing or checking.
Python does not enforce this rule. If an override has a different signature or returns something unexpected, Python accepts it and the failure shows up later, at the call site. Keeping the contract is your job.
What a caller depends on
Every method has a contract that callers rely on, even if it is undocumented:
| Part of the contract | Safe override | Breaking override |
|---|---|---|
| Parameters | Same, or more optional parameters | Fewer, renamed, or newly required parameters |
| Accepted input | Same or wider | Rejects values the parent accepted |
| Return value | Same type, or a more specific one | A different kind of object, or `None` |
| Exceptions | The same ones, or subclasses of them | New unrelated exceptions |
| Side effects and state | Same guarantees | Breaks rules the parent kept |
The rest of the chapter works through these rows.
Keep the signature compatible
A caller may pass arguments by position or by keyword. The override has to accept every call the parent accepted.
class Notifier:
def send(self, message, urgent=False):
return f"[notice] {message}"
class SmsNotifier(Notifier):
def send(self, message): # dropped the urgent parameter
return f"[sms] {message}"
def alert(notifier, text):
return notifier.send(text, urgent=True)
print(alert(Notifier(), "disk full"))
try:
print(alert(SmsNotifier(), "disk full"))
except TypeError as exc:
print("TypeError:", exc)alert() works with Notifier and fails with SmsNotifier. The error is raised inside alert(), which did nothing wrong. The fix is to keep the parameter, even if the subclass ignores it:
class SmsNotifier(Notifier):
def send(self, message, urgent=False):
prefix = "[sms URGENT]" if urgent else "[sms]"
return f"{prefix} {message}"An override may add parameters, but they must have defaults. A new required parameter breaks every existing call.
class EmailNotifier(Notifier):
def send(self, message, urgent=False, cc=None):
extra = f" (cc {cc})" if cc else ""
return f"[email] {message}{extra}"If the parent uses *args, **kwargs to pass options through, keep that shape in the override and forward the extra arguments to super().
Do not narrow what you accept
The parent method defines which inputs are valid. An override may accept more than that. It must not accept less.
class Storage:
def save(self, name, data):
return f"saved {name!r} ({len(data)} bytes)"
class StrictStorage(Storage):
def save(self, name, data):
if " " in name:
raise ValueError("names cannot contain spaces")
return super().save(name, data)
def backup(storage):
return storage.save("monthly report", b"...")
print(backup(Storage()))
try:
print(backup(StrictStorage()))
except ValueError as exc:
print("ValueError:", exc)backup() was correct for Storage, because the parent allowed spaces. StrictStorage added a precondition the caller could not know about. If a subclass needs stricter input, it is probably not a true specialization. Consider a separate class, or put the rule in the parent so every caller knows it.
Return the same kind of thing
Callers use the return value in ways that depend on its type. Returning a more specific type is fine. Returning something with fewer capabilities is not.
class Catalog:
def names(self):
return ["apple", "pear"]
class LazyCatalog(Catalog):
def names(self):
yield "apple"
yield "pear"
def count(catalog):
return len(catalog.names())
print(count(Catalog())) # 2
try:
print(count(LazyCatalog()))
except TypeError as exc:
print("TypeError:", exc)A list supports len(), indexing, and repeated iteration. A generator supports none of these except a single pass of iteration. A related mistake is an override that forgets return and so returns None. This happens often when an override calls super().method() to add behavior and drops the result:
class Report:
def title(self):
return "Report"
class DraftReport(Report):
def title(self):
super().title() + " (draft)" # bug: result is discardedDraftReport().title() returns None. Write return super().title() + " (draft)".
Raise the same family of exceptions
Callers write try/except for the errors the parent documents. An override that raises a different, unrelated exception bypasses those handlers.
class Repository:
def get(self, key):
raise KeyError(key)
class DbRepository(Repository):
def get(self, key):
raise ConnectionError("database offline") # caller never expected thisThere are two safe options. Raise a subclass of the exception the parent raises, or document the new exception in the parent's contract so all callers handle it. A common choice for a library is a base exception class (for example RepositoryError) that every override uses.
Preserve state rules
The classic example is a Square that inherits from Rectangle. Mathematically a square is a rectangle. In code, Rectangle promises that width and height change independently, and Square cannot keep that promise.
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
def set_width(self, w):
self.w = w
def area(self):
return self.w * self.h
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
def set_width(self, w):
self.w = w
self.h = w # keeps it square, but changes the height too
def widen(rect):
height = rect.h
rect.set_width(10)
assert rect.area() == 10 * height, "setting width changed the height"
return rect.area()
print(widen(Rectangle(2, 3))) # 30
try:
widen(Square(3))
except AssertionError as exc:
print("AssertionError:", exc)Every method signature matches, yet the override breaks the behavior callers rely on. Type checkers cannot catch this. Only tests and careful thought can. The usual remedies:
- Make the objects immutable, so no
set_widthexists to break. - Give
RectangleandSquarea common parent such asShapethat promises onlyarea(). - Use composition, covered in a later chapter, when the "is-a" relationship does not hold for behavior.
Use hooks to limit what subclasses can break
When a parent method has steps that must always happen, such as validation or logging, do not make subclasses re-implement them. Keep the public method in the parent and let subclasses override a smaller hook.
class Task:
def run(self):
self.before()
result = self.execute()
self.after(result)
return result
def before(self):
print("starting")
def execute(self):
raise NotImplementedError
def after(self, result):
print("finished with", result)
class SumTask(Task):
def __init__(self, numbers):
self.numbers = numbers
def execute(self):
return sum(self.numbers)
print(SumTask([1, 2, 3]).run())Callers use run(), which subclasses do not touch. The fixed sequence (before, execute, after) stays intact, and each subclass supplies only the part that differs. This is the template method pattern.
Let tools catch what they can
Two tools help with the checkable parts of the contract.
- Type checkers such as mypy and pyright report override signatures that are incompatible with the parent, including a missing parameter and a narrower argument type.
- Since Python 3.12,
typing.overridemarks a method as an intended override. A checker then warns if the parent has no such method, which catches typos and renames.
from typing import override
class Base:
def greet(self, name: str) -> str:
return f"Hello, {name}"
class Friendly(Base):
@override
def greet(self, name: str) -> str:
return f"Hi, {name}!"The decorator does not change runtime behavior. It is only a signal for checkers and readers.
Common mistakes
- Dropping a parameter or renaming it. Callers that pass it by keyword fail.
- Adding a required parameter instead of one with a default.
- Validating more strictly than the parent and raising on input the parent allowed.
- Forgetting to return the value of
super().method(). - Returning a generator,
None, or another type where callers expect a list or a number. - Raising a new exception type that no existing caller handles.
- Overriding a method to do nothing (
pass) to disable a feature. Callers still call it and expect the parent's effect. If a subclass cannot support a method, the class probably should not inherit from that parent.
Exercise
A parent class has def parse(self, text, strict=False) that returns a list of tokens. A subclass overrides it as def parse(self, text, strict=False, *, limit) and returns a tuple. Name two ways this breaks callers of the parent, and say how to fix each.
Show answer
First, limit is a required keyword-only parameter, so existing calls such as obj.parse("a b") raise TypeError. Fix it by giving limit a default, for example limit=None. Second, the return type changed from list to tuple, so callers that append to the result or rely on list behavior fail. Fix it by returning a list (or a list subclass).
Exercise
Penguin inherits from Bird, and Bird.fly() returns a string describing the flight. Penguin.fly() raises NotImplementedError. A function migrate(birds) calls fly() on each bird. Why is this a substitutability problem, and what is one redesign?
Show answer
migrate() works for every Bird except Penguin, so a Penguin cannot be used wherever a Bird is expected. One redesign splits the hierarchy: Bird has the shared behavior, and a subclass or mixin such as FlyingBird adds fly(). migrate() then takes FlyingBird objects, and Penguin inherits only from Bird.
Exercise
Why does the Task.run() template method make subclass mistakes less likely than letting each subclass override run() directly?
Show answer
Callers use run(), which stays defined in the parent, so the order of steps (before, execute, after) cannot be changed or forgotten by a subclass. A subclass overrides only the small hook (execute) and cannot skip the shared logging or validation.