DEV Community

Discussion on: Why I stay away from Python type annotations

Collapse
 
martinthoma profile image
Martin Thoma • Edited

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...

Collapse
 
trodiz profile image
trodiz

You can read the doc string and still understand that a dictionary is expected. Which is exactly what developers have been doing well before version 3.5. And you can be as verbose or succinct as you like. Type annotations can only work with previously known types. python's ability to do polymorphism will be stifled by your type checkers. a dynamically defined type, which should work with the function will still throw an error in your type checker. This is what OP meant by saying "going specific to generic".

In your final paragraph you demand OP to choose another language even when they clearly stated what makes python a great language. You even repeated those points yourself. If I'm willing to annotate and type check everything in my code, I'd rather choose Rust or go for the added benefit of performance. If you're the one who is looking for static typing from a slow dynamically typed language, maybe, just maybe, it is you who need to look for another language.