DEV Community

Jesse Warden
Jesse Warden

Posted on • Originally published at jessewarden.com

Python Has Types, They Help

Seeing these Python projects being worked on by junior devs with decent test coverage, but zero types amongst code that’s doing a lot of data transformation is… disappointing. I worry for those teams. If your tech lead has not told you, Python has optional, gradual types.

These can reduce bugs and reduce the amount of unit tests you need to write if you are willing to put in the work. You import the types, and decorate (aka annotate) your code with them. Over time you learn to narrow, or “shrink” how many types your code can handle (Any vs String). If you have nothing, you can just start adding a few; you don’t need to rewrite your code, nor annotate all of your code; you can do a little at a time.

https://docs.python.org/3/library/typing.html

IDE’s (PyCharm, VSCode, etc) will give better code hints, and when running compilers, called type checkers, that check for errors but don’t actually modify your code. They’ll instantly point out where your types are wrong so you can fix them. Here are 4 options; I’ve used mypy and it’s pretty quick, but that was 3 years ago so I’m sure things have improved in speed and readability:

You still should utilize unit and acceptance tests, but types will help significantly reduce the amount of unit tests you need to write.

Top comments (0)