Can I use duck typing with mypy?
Mypy provides support for both nominal subtyping andstructural subtyping.Structural subtyping can be thought of as “static duck typing”.Some argue that structural subtyping is better suited for languages with ducktyping such as Python. Mypy however primarily uses nominal subtyping,leaving structural subtyping mostly opt-in (except for built-in protocolssuch as Iterable
that always support structural subtyping). Here are somereasons why:
- It is easy to generate short and informative error messages whenusing a nominal type system. This is especially important whenusing type inference.
- Python provides built-in support for nominal
isinstance()
tests andthey are widely used in programs. Only limited support for structuralisinstance()
is available, and it’s less type safe than nominal type tests. - Many programmers are already familiar with static, nominal subtyping and ithas been successfully used in languages such as Java, C++ andC#. Fewer languages use structural subtyping. However, structural subtyping can also be useful. For example, a “public API”may be more flexible if it is typed with protocols. Also, using protocol typesremoves the necessity to explicitly declare implementations of ABCs.As a rule of thumb, we recommend using nominal classes where possible, andprotocols where necessary. For more details about protocol types and structuralsubtyping see Protocols and structural subtyping and PEP 544.