Sub topic 1
Subtyping by declaration: classes and inheritance
Prerequisites
This chapter assumes you can:
- Write Python functions and classes, including inheritance with
class Child(Parent). - Read basic type hints on parameters and return values.
- Run or imagine a static type checker such as mypy or pyright. A static type checker reads your code and reports type errors without running it.
What nominal subtyping means
A type B is a subtype of type A if code can use a B anywhere an A is expected. Python has one long-standing way to establish that relationship: you declare it by naming the parent class.
This is called nominal subtyping. "Nominal" means "by name". The checker asks whether you wrote class B(A) somewhere in the inheritance chain. It does not look at what methods B has.
class Animal:
def speak(self) -> str:
raise NotImplementedError
class Dog(Animal):
def speak(self) -> str:
return "Woof"
class Robot:
def speak(self) -> str:
return "Beep"
def announce(animal: Animal) -> None:
print(animal.speak())
announce(Dog()) # accepted: Dog is declared a subclass of Animal
announce(Robot()) # rejected by a type checker: Robot never names Animal as a parentRobot has the same speak method as Animal. The checker still reports an error, because the declaration is missing. If you run the file, announce(Robot()) works and prints Beep. Type hints are not enforced at runtime, so the error only appears when you run a checker.
How the relationship is checked
The relationship is transitive. If Puppy inherits from Dog and Dog inherits from Animal, then Puppy is also an Animal.
At runtime, isinstance and issubclass follow the same chain. Python walks the class's method resolution order (MRO), which is the ordered list of parent classes it searches for attributes.
class Animal:
pass
class Dog(Animal):
pass
class Puppy(Dog):
pass
class Robot:
pass
print(isinstance(Puppy(), Animal)) # True
print(issubclass(Dog, Animal)) # True
print(issubclass(Robot, Animal)) # FalseSubclasses must honor the parent's contract
Declaring a subclass is a promise. Wherever the parent works, the child must work too. This rule is the Liskov substitution principle. A type checker enforces its mechanical part by checking method overrides.
class Animal:
def speak(self) -> str:
return "..."
class Cat(Animal):
def speak(self, loudly: bool) -> str: # error: incompatible override
return "MEOW" if loudly else "meow"Code that holds an Animal calls speak() with no arguments. Cat.speak requires one, so substituting a Cat would break that call. Checkers report this as an incompatible override. Giving loudly a default value (loudly: bool = False) fixes it.
The usual override rules are:
| Part of the method | What a subclass may do |
|---|---|
| Parameters | Accept the same types or broader ones. Extra parameters need defaults. |
| Return type | Return the same type or a narrower one. |
| Method name | Keep it. Renaming removes the inherited method for callers. |
Costs of declaring everything
Nominal subtyping is explicit and easy to reason about. It also has costs:
- Coupling. The subclass must import and name its parent, so the module that defines
Dogdepends on the module that definesAnimal. - Closed to outsiders. You cannot make a class from a third-party library inherit from your base class without wrapping it or subclassing it yourself.
- Heavier hierarchies. Every shared capability needs a named parent, and multiple inheritance can get tangled quickly.
Structural subtyping, introduced in the next chapters, removes these costs. Compatibility there depends on what a class provides, not on what it declares.
Exercise
Given class Base: ..., class Child(Base): ... and class Stranger: ... (where Stranger has the same methods as Base), which of Child() and Stranger() does a type checker accept for a parameter annotated Base, and why?
Show answer
It accepts Child() because Child declares Base as a parent, so it is a nominal subtype. It rejects Stranger(). Stranger never names Base as a parent, and nominal subtyping ignores matching methods.