Since PEP 484 in 2014, type hints and the mypy tool have become an important part of the Python ecosystem. Type hints provide an incremental way to add information to the Python source, which can be checked by external tools like mypy and some IDE environments like PyCharm. Type hint checking can be part of a CI/CD pipeline to provide confidence that the code is likely to behave properly at run-time. Python’s Duck-Typing approach can lead to working code that is hard to describe with available type hints.
This tutorial expects hands-on participation with a large number of small examples. It will start with some simple cases of type hints. We’ll look at complex data structures and ways to factor the complexity out of the type hints. We’ll look at circular type references, common on problems where graphs are represented. The techniques for “debugging” type hints will focus on exposing the mypy reasons about the source code.
We’ll look at two very easy and useful ways to incorporate type hints into class definitions using the typing.NamedTuple class and the @dataclass decorator. We’ll also look at situations where the type: ignore comment can be appropriate. Another important topic will touch on how we can write a stub for a library where the code doesn’t have type hints.