Home  >  Article  >  Backend Development  >  Python Has Types, They Help

Python Has Types, They Help

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 02:09:02995browse

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:

  • mypy
  • pyright
  • pyre
  • pytype

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

The above is the detailed content of Python Has Types, They Help. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn