Sub topic 1
Subtyping by declaration: classes and inheritance
Before protocols make sense, you need to know what they replace. In most Python code that uses type hints, a class counts as a subtype of another class only because its definition says so. This chapter covers that rule, which is called nominal subtyping. It shows what a type checker does with it and where it starts to cause friction. The rest of the tutorial builds on that friction.
Prerequisites
This chapter assumes you can already do the following:
- Write Python functions and classes, including
super()and method overriding. - Read and write basic type hints on parameters and return values.
- Use abstract base classes from the
abcmodule at a basic level. - Run a static type checker such as mypy or pyright. A static type checker is a tool that reads your code and reports type errors without running it.
The examples are plain Python 3.9 or later. The error messages in comments are paraphrased, because the exact wording differs between mypy and pyright.
What "nominal" means
Nominal subtyping means that type compatibility depends on names and declarations. Class B is a subtype of class A only if B lists A among its bases, directly or through a chain of parents. The shape of B does not matter. A method called area with the right signature does not make B a subtype of anything. The declaration class B(A) does.
A subtype is a type that can be used wherever its parent type is expected. This rule is the substitution principle. If a function asks for an A, you may pass a B, and the function must keep working.
A worked example
Here is a small hierarchy with an abstract base class:
from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self) -> float:
...
class Circle(Shape):
def __init__(self, radius: float) -> None:
self.radius = radius
def area(self) -> float:
return math.pi * self.radius ** 2
class Square(Shape):
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side ** 2
def total_area(shapes: list[Shape]) -> float:
return sum(shape.area() for shape in shapes)
print(round(total_area([Circle(1.0), Square(2.0)]), 3))The output is 7.142. The checker accepts the call because Circle and Square both declare Shape as a base class. Inside total_area, the checker knows every element has an area() method returning float, so shape.area() type-checks.
Now consider the reverse direction:
def describe(shape: Shape) -> str:
return f"area={shape.area():.2f}"
describe(Circle(1.0)) # accepted: Circle is declared as a Shape
describe("circle") # rejected: str is not declared as a ShapeThe second call fails because str has no Shape in its base classes. A checker reports something like Argument 1 to "describe" has incompatible type "str"; expected "Shape". Python itself would raise AttributeError only when the line runs.
How the checker walks the hierarchy
Every class has a method resolution order (MRO). This is the ordered list of classes Python searches when it looks up an attribute. Type checkers use the same list for declared subtyping. To decide whether Circle is acceptable where Shape is expected, the checker asks whether Shape appears in the MRO of Circle. You can look at that list yourself:
print([cls.__name__ for cls in Circle.__mro__])
# ['Circle', 'Shape', 'ABC', 'object']The check is a membership test on declared parents. It never compares method names or signatures between unrelated classes. The following diagram shows the relationships from the example, plus one class that has no declared link.
LegacyCircle is drawn without an arrow because it declares no parent. That absence is the subject of a later section.
Inheritance carries two things at once
When you write class Circle(Shape), you get two separate effects:
- Type relationship. The checker treats
Circleas aShape. - Implementation reuse.
Circleinherits any concrete methods and attributes thatShapedefines.
For an abstract class like Shape there is a third effect at runtime. Python refuses to instantiate a subclass that has not implemented every @abstractmethod:
class Triangle(Shape):
pass
try:
Triangle()
except TypeError as error:
print(error)Python raises TypeError here, with a message saying the abstract class Triangle cannot be instantiated without an implementation for area. The exact wording varies slightly between Python versions. This enforcement is useful, and it is a runtime feature of ABC. It is not part of nominal subtyping itself. A plain base class with no ABC still gives you the type relationship, but nothing stops you from forgetting a method.
The checker also polices overrides
Declaring a parent is a promise. The checker verifies that each override honors the parent's signature. The rule behind this is the Liskov substitution principle: code written for the parent must keep working when it receives a child.
class Base:
def scale(self, factor: float) -> float:
return factor
class Child(Base):
def scale(self, factor: int) -> float: # error: narrows the parameter type
return float(factor)The override accepts only int where the parent accepts any float. A caller holding a Base could legally pass 1.5, and a Child would then break. The checker reports an incompatible override. The safe directions are:
- Parameters may be widened. The child may accept more than the parent does.
- Return types may be narrowed. The child may promise more than the parent does.
This is the same variance idea that returns later in the chapter on generic protocols.
Where declaration-based typing gets awkward
Nominal subtyping is simple and predictable, but it has real costs. Each cost points toward the same fix.
You cannot retrofit classes you do not own
Suppose a third-party library gives you a class that happens to fit your needs:
class LegacyCircle:
"""Pretend this comes from a library you cannot edit."""
def __init__(self, radius: float) -> None:
self.radius = radius
def area(self) -> float:
return 3.14159 * self.radius ** 2
print(total_area([Circle(1.0), LegacyCircle(1.0)]))
# Runs fine and prints 6.28318.
# A type checker rejects it: "LegacyCircle" is not a "Shape".At runtime the code works, because LegacyCircle has area(). The checker rejects it anyway, because Shape is not among its bases. Your options all cost something:
- Subclass it with
class MyLegacyCircle(LegacyCircle, Shape). You then have to construct your own subclass everywhere, and objects the library itself creates will not be instances of it. - Wrap it in an adapter class that inherits from
Shapeand delegates to the library object. This is correct but adds boilerplate. - Silence the checker with
# type: ignoreorcast. This hides the problem and gives up the check on that line.
Libraries become coupled to your base class
If you publish Shape in a library, every user must import it and inherit from it, even if they only wanted to call your functions. Your base class becomes a dependency of their code.
Base classes grow
Because a base class doubles as a place for shared code, it tends to collect helper methods. A function that needs only area() then demands a type that brings along everything else.
Runtime registration is invisible to the checker
ABC offers Shape.register(LegacyCircle), which makes isinstance(LegacyCircle(1.0), Shape) return True at runtime. This is called a virtual subclass. Static checkers generally do not follow register calls. So registration fixes the runtime question and leaves the static question open.
Shape.register(LegacyCircle)
print(isinstance(LegacyCircle(1.0), Shape)) # True at runtime
# Type checkers still treat LegacyCircle as unrelated to Shape.Because of this, runtime behavior and static analysis can disagree about the same class.
Summary of the nominal model
| Question | Nominal answer |
|---|---|
| What makes `B` a subtype of `A`? | `A` appears in the bases of `B`, directly or indirectly. |
| Does a matching method make it a subtype? | No. |
| Can you add the relationship to a class you do not own? | Not without subclassing, wrapping or ignoring the checker. |
| What does the checker verify on override? | Parameters may widen and return types may narrow. |
| Who enforces abstract methods? | Python at instantiation time, if the base uses `ABC`. |
Common mistakes
- Assuming a matching method is enough. The checker will not infer a relationship from
area()alone. Duck typing at runtime and nominal typing in the checker answer different questions. - Inheriting only to satisfy the checker. Adding a base class to your own class just to pass an annotation can drag in unwanted behavior or force awkward
__init__calls. - Forgetting
ABC. A base class with@abstractmethodbut withoutABCorABCMetaas its metaclass does not stop instantiation. The decorator is only enforced byABCMeta. - Narrowing parameter types in an override. This breaks substitution and the checker flags it.
Exercise
A library class Report has a method render(self) -> str, but it does not inherit from your abstract class Renderable, which declares the same method. You pass a Report to a function annotated def show(item: Renderable) -> None. The code runs correctly. What does a static type checker report, and why?
Show answer
It reports an incompatible argument type: Report is not a Renderable. Under nominal subtyping, compatibility requires Renderable to appear in the bases of Report, and a matching render method does not count. The code still runs because Python only looks up render at call time.
Exercise
Given class Base: with def run(self, count: int) -> int: ..., which override is accepted by a checker: def run(self, count: float) -> int or def run(self, count: bool) -> int? Explain using the direction of allowed change.
Show answer
The one taking float is accepted. Parameters may be widened in an override, and float accepts every int that Base.run accepts. The bool version narrows the parameter, so a caller passing an arbitrary int to a Base reference could break it, and the checker flags it.
Exercise
You call Shape.register(LegacyCircle). What changes at runtime, and what does not change for a static type checker?
Show answer
At runtime, isinstance(LegacyCircle(1.0), Shape) becomes True because LegacyCircle is now a virtual subclass. Static checkers generally do not follow register calls, so they still treat LegacyCircle as unrelated to Shape and reject it where a Shape is expected.