Sub topic 12
Overriding without breaking callers
This chapter assumes you can define classes, use self, call super() in a subclass, and understand polymorphism. It covers how to override a method so that code written for the parent class keeps working with the subclass.
The substitutability rule
A subclass is substitutable when code that works with the parent class also works, unchanged, with any subclass instance. This is often called the Liskov substitution principle. Python does not enforce it. The interpreter accepts any override with any signature or return type, so you have to check it yourself.
A caller that holds an Animal makes three assumptions: the method accepts the arguments the parent accepts, it returns the kind of value the parent returns, and it does not demand more than the parent demanded. An override breaks callers when it violates any of these.
Keep the signature compatible
An override may accept more than the parent does. It should not accept less. Adding optional parameters is safe. Removing parameters or making them required is not.
class Report:
def render(self, data, title="Report"):
return f"{title}: {len(data)} rows"
class ShortReport(Report):
def render(self, data): # drops the title parameter
return f"{len(data)} rows"
class DetailedReport(Report):
def render(self, data, title="Report", verbose=False): # adds an optional parameter
text = super().render(data, title)
return text + (" (verbose)" if verbose else "")
def publish(report, data):
return report.render(data, title="Sales")
print(publish(DetailedReport(), [1, 2, 3])) # Sales: 3 rows
try:
print(publish(ShortReport(), [1, 2, 3]))
except TypeError as exc:
print("TypeError:", exc)DetailedReport works with publish(). ShortReport fails because it no longer accepts title.
Keep the return type compatible
Callers use the return value, so an override must return something they can use in the same way. If the parent returns a string, returning None or a tuple will break the caller.
class Parser:
def parse(self, text):
return text.split(",")
class BadParser(Parser):
def parse(self, text):
print("parsing") # returns None instead of a list
def count_fields(parser, text):
return len(parser.parse(text))
print(count_fields(Parser(), "a,b,c")) # 3
try:
count_fields(BadParser(), "a,b,c")
except TypeError as exc:
print("TypeError:", exc)Returning a more specific type is fine. A subclass of list is still a list.
Do not tighten the rules
An override must not reject inputs the parent accepted. It also must not break guarantees the parent made about its results or about the object's state.
class Account:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
self.balance -= amount
return self.balance
class LimitedAccount(Account):
def withdraw(self, amount):
if amount > 100:
raise ValueError("limit is 100") # parent had no such limit
return super().withdraw(amount)A caller that withdraws 500 from an Account now gets an exception when it is handed a LimitedAccount. If the limit is a real requirement, LimitedAccount is probably not an Account in the sense the callers assume. Document the limit in the parent contract, or restructure the design.
The classic warning sign
The standard example is a Square that inherits from Rectangle. A rectangle lets you set width and height independently. A square must keep them equal, so its setters change both values. Code that sets the width to 5 and the height to 4 and then expects an area of 20 gets 16 from a square. The subclass is valid geometry, but it breaks the parent's behavioral contract.
A practical checklist
- Keep the parameter names, order, and defaults of the parent, and add only optional parameters.
- Return the same type as the parent, or a subtype of it.
- Raise only the exceptions the parent could raise, or subclasses of them.
- Preserve documented guarantees about state.
- Run the parent's tests against each subclass. A test suite written for the base class is a direct check of substitutability.
Exercise
A parent method is def save(self, path, overwrite=False). Which override is safe for existing callers: def save(self, path), def save(self, path, overwrite=False, compress=False), or def save(self, path, overwrite)?
Show answer
Only def save(self, path, overwrite=False, compress=False) is safe. It accepts every call the parent accepted and adds an optional parameter. The first drops overwrite, so save(p, overwrite=True) raises TypeError. The third makes overwrite required, so save(p) raises TypeError.
Exercise
A subclass of Account raises ValueError for withdrawals over 100, but Account.withdraw has no limit. Why does this break callers, and what are two ways to fix the design?
Show answer
Callers written for Account withdraw any amount and do not expect ValueError, so the subclass adds a precondition the parent did not have. One fix is to put the limit into the parent's contract so every account enforces it. Another is to avoid inheritance and have the limited account hold an Account and apply its own rules (composition).