DEV Community

Discussion on: Why I stay away from Python type annotations

Collapse
martinthoma profile image
Martin Thoma • Edited on

I disagree with pretty much every point you made:

  1. Protection: It's not about the runtime. In my projects, I let mypy run in CI. This means the types of every production code is checked. Yes, there are important notes like you need to set certain mypy flags so that everything is actually checked. The case that happens most often to me is a check for "None" which I forgot.
  2. Readability: You pretty bad usage of types and still it helps. In the typed example, I know that a dictionary is expected. You also later in that section mentioned a couple of points how the annotation can be improved. One part that I didn't see was the usage of pydantic/dataclasses and using NewType. For Dict[str, Any] and str types you can typically improve this quite a bit. This also typically changes the architecture a bit to move validation of data to an earlier stage. Hence the usage of type annotations leads to a better architecture and thus more readable/maintainable code.
  3. Documentation: I wouldn't get rid of documentation - if it exists. If you use type annotations, you can automatically check if they are correct and you can also check if they exist. For docstrings ... well, it's mixed. I've seen developers who add them everywhere, developers who don't add them anywhere, teams using numpy/sphinx/google style... this is a complete own story.
  4. Python vs the world: Libraries, personal preference, speed of development, the ecosystem. If neither of them is a good reason for you to use Python, then maybe you should use another language.

In case you want to learn more about type annotations, have a look at medium.com/analytics-vidhya/type-a...