LSP

LSP — Liskov Substitution Principle

"If S is a subtype of T, then objects of type T may be replaced with objects of type S without altering any of the desirable properties of the program (correctness, task performed, etc.)." — Barbara Liskov & Jeannette Wing, A Behavioral Notion of Subtyping (ACM TOPLAS, 1994); the idea was first sketched in Data Abstraction and Hierarchy (Liskov, 1987).

"Subtypes must be substitutable for their base types." — Robert C. Martin, modern reformulation


Core idea

Anywhere a base type T is used, you should be able to swap in any subtype S and the program should keep working correctly. If substitution breaks the logic, that is an LSP violation. The inheritance is built wrong.


Why it matters

LSP violation Consequence
isinstance(x, Bird) lets you call bird.fly(), but Penguin.fly() crashes The caller cannot trust the type
The subclass throws new exceptions The error handling "above" does not expect them
The subclass changes the meaning of the method The caller gets a surprise, not a bug message
The subclass has stricter preconditions Rectangle.set_width(10) works, Square.set_width(10) also changes height
Liskov compatibility is broken OCP is broken too — new subclasses become unsafe

Without LSP, OCP does not work. If a new subclass can break a consumer, adding it is not safe.


Formal rules of LSP

(The rules are framed in Design by Contract terms — Bertrand Meyer, Object-Oriented Software Construction (1988). LSP formalises the contract side of subtyping.)

The subclass may:

  1. ✅ Accept wider parameter types (contravariance in input)
  2. ✅ Return narrower types (covariance in output)
  3. ✅ Throw the same or narrower exceptions

The subclass may not:

  1. ❌ Narrow preconditions ("I only accept positive int" when the parent accepts any int)
  2. ❌ Relax postconditions ("I might return None" when the parent promised never None)
  3. ❌ Break the base class invariants
  4. ❌ Throw exceptions the parent did not throw

The short version: the subclass should behave "no worse" than the parent, in every sense.


Classic example: Rectangle vs Square

It seems intuitive:

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def set_width(self, w):
        self.width = w

    def set_height(self, h):
        self.height = h

    def area(self):
        return self.width * self.height

class Square(Rectangle):                # ← feels natural: a square IS-A rectangle
    def __init__(self, side):
        super().__init__(side, side)

    def set_width(self, w):
        self.width = w
        self.height = w                  # ← keep the square invariant

    def set_height(self, h):
        self.width = h
        self.height = h

And here is why it violates LSP:

def resize_to_5x10(rect: Rectangle):
    rect.set_width(5)
    rect.set_height(10)
    assert rect.area() == 50

resize_to_5x10(Rectangle(2, 3))   # ✅ works, area = 50
resize_to_5x10(Square(2))         # ❌ crashes, area = 100 (10x10)

The caller expects that after set_width(5) and set_height(10) the rectangle is 5×10. The Rectangle behaves that way. The Square does not, because its invariant "width = height" is stronger than the parent's.

Mathematically a square is a rectangle. Behaviourally it is not. That is the difference between essence and behaviour, and OOP cares about behaviour.

How to do it right

Do not inherit. Split into siblings under a shared Protocol:

from typing import Protocol
from dataclasses import dataclass

class HasArea(Protocol):
    def area(self) -> float: ...

@dataclass(frozen=True)
class Rectangle:
    width: float
    height: float

    def area(self) -> float:
        return self.width * self.height

@dataclass(frozen=True)
class Square:
    side: float

    def area(self) -> float:
        return self.side ** 2

# Caller:
def total_area(shapes: list[HasArea]) -> float:
    return sum(s.area() for s in shapes)

total_area([Rectangle(2, 3), Square(5)])   # ✅ works for both

Now:


Second classic example: Bird vs Penguin

class Bird:
    def fly(self) -> None:
        print("flying")

class Penguin(Bird):
    def fly(self) -> None:
        raise NotImplementedError("penguins do not fly")   # ❌

A caller writing def migrate(bird: Bird): bird.fly() expects the method to work. A penguin throws. LSP broken.

How to do it right

Split the capabilities:

class Bird(Protocol):
    def chirp(self) -> str: ...                # all birds can do this

class FlyingBird(Bird, Protocol):              # a subset — the ones that fly
    def fly(self) -> None: ...

class Eagle:
    def chirp(self): return "screech"
    def fly(self): print("soaring")

class Penguin:
    def chirp(self): return "honk"
    # NO fly() — a penguin is not a FlyingBird

def migrate(bird: FlyingBird):                  # ← the type is restricted
    bird.fly()

migrate(Eagle())     # ✅
migrate(Penguin())   # ❌ mypy / IDE complains right away

This is ISP. LSP and ISP are a pair that solves this whole class of problems.


How to spot an LSP violation

Red flags in the subclass

  1. raise NotImplementedError in an override — the subclass cannot do what the parent promised.
  2. The override starts with if isinstance(...): — you are narrowing the precondition.
  3. The subclass adds validation the parent did not have — you are narrowing the input.
  4. The override returns None or Optional when the parent returned a concrete value — you are relaxing the output.
  5. The override throws an exception the parent did not throw — you are breaking the contract on exceptions.

Red flags in the consumer

  1. isinstance check before calling a method — "oh, for Square I do something else".
  2. The caller needs try/except specifically for the subclass — the subclass is not compatible.
  3. "For Square we do X, for Rectangle we do Y" — side logic for a subtype.

LSP and Python: what to expect

The type checker (mypy, pyright) catches some violations

class Base:
    def process(self, x: int) -> str: ...

class Child(Base):
    def process(self, x: int, extra: str) -> str: ...   # ← mypy: incompatible

The type checker stops this (signature change). But semantic violations (square vs rectangle) it does not catch. You need tests for that.

Python allows "unsafe" overrides

In a dynamic language you can override anything. LSP in Python is discipline, not enforcement.


Anti-patterns

1. NotImplementedError as a placeholder

class FlyingObject:
    def fly(self): ...

class Ground(FlyingObject):
    def fly(self): raise NotImplementedError    # ← Ground is not a FlyingObject

If the subclass "cannot", it is not the same type. Split into siblings.

2. Narrowing input types

class Sender:
    def send(self, msg: str | bytes): ...

class StrictSender(Sender):
    def send(self, msg: str):                    # ← only str, narrowed
        if not isinstance(msg, str):
            raise TypeError(...)

The bytes case that worked with Sender fails with StrictSender. Violation.

3. Relaxing output types

class UserRepo:
    def get(self, id: int) -> User: ...           # always User

class CachedUserRepo(UserRepo):
    def get(self, id: int) -> User | None:        # ← could be None
        return self._cache.get(id)

A caller expecting User now sometimes gets None, and user.name crashes with AttributeError. Violation.

4. New exceptions

class Repository:
    def save(self, x): ...                        # documented: returns None or raises IOError

class TransactionalRepo(Repository):
    def save(self, x):
        ...
        if not self._tx.active:
            raise TransactionError(...)            # ← new exception!

The old except IOError: handler misses the new error. Violation.

5. The subclass invariant is stronger than the parent's

The classic Square-vs-Rectangle. The subclass adds a constraint the parent did not have. The caller working with the parent does not know about it and breaks.


Relationship to other principles

Principle How LSP relates
OCP Without LSP, OCP is not safe: a new subclass can break existing code
ISP Separating interfaces ("who flies", "who swims") avoids inheriting "extras"
Composition > inheritance An LSP violation is often solved by composition
Protocol Structural polymorphism is naturally LSP-friendly: implement the methods, you are substitutable

Rules of thumb

  1. If is-a sounds weird, do not inherit. Test it by behaviour: can you substitute it in every parent context?
  2. An override without super() is suspicious. Are you replacing the behaviour entirely? Maybe you wanted a separate class?
  3. isinstance in the consumer = LSP failure. The consumer should not "know" about subtypes.
  4. Exceptions the subclass throws are a subset of the parent's.
  5. Same or wider signature on input, same or narrower on output.
  6. The subclass invariant is the same or weaker, never stronger.
  7. Substitution test: in your parent's tests, replace every occurrence of Base with Derived. Do they still pass?

One-line summary

A subclass should behave everywhere the way callers expect from the parent type. If it does not, it is not a subclass. Composition or sibling types under a Protocol is often the right answer.