Protocols and structural subtyping

Mypy supports two ways of deciding whether two classes are compatibleas types: nominal subtyping and structural subtyping. Nominal_subtyping is strictly based on the class hierarchy. If class Dinherits class C, it’s also a subtype of C, and instances ofD can be used when C instances are expected. This form ofsubtyping is used by default in mypy, since it’s easy to understandand produces clear and concise error messages, and since it matcheshow the native isinstance check works – based on classhierarchy. _Structural subtyping can also be useful. Class D isa structural subtype of class C if the former has all attributesand methods of the latter, and with compatible types.

Structural subtyping can be seen as a static equivalent of ducktyping, which is well known to Python programmers. Mypy providessupport for structural subtyping via protocol classes describedbelow. See PEP 544 for the detailed specification of protocolsand structural subtyping in Python.