Silence the static type checker with the robustness principle

Learn to write type-safe Python without getting slaughtered by the type checker

Niels Cautaerts
Level Up Coding

--

Type hints, in combination with a static type checker like mypy or pyright, can substantially improve the robustness and maintainability of Python code. Being able to detect and fix an entire class of bugs before ever running the program is extremely useful; it enables fearless refactoring and substantially reduces the burden of writing tests.

Additionally, type hints serve as minimal documentation that helps users and maintainers alike figure out quickly what a piece of code is supposed to do, or how it is supposed to be used.

However, many Python developers — especially those without any experience in a strongly typed language — struggle with type hinting. Beyond trivial examples with built-in data types, satisfying all the rules of the type checker quickly turns into a bloodbath of errors. After lengthy battles with the type checker, most developers capitulate by using copious amounts of Any annotations or # type: ignore comments. This ultimately sidesteps the safety guarantees we gain from type checking.

One major reason Pythonistas struggle with type hinting is because they don’t really know the rules of battle. Type hints with…

--

--