Hacker News new | ask | show | jobs
by rrauenza 403 days ago
I adopted Python type annotations on a new project I was writing. Requirements shifted a lot as well as the implementation.

It was amazing. I could refactor quickly after changing a dataclass, field name, function arguments, type, etc. I just ran mypy and it immediately told me everywhere I needed to update code to reference the new refactored type or data structure.

Then only after it was mypy clean, I ran the unit tests.

3 comments

My style has changed over time and part of it is thanks to static type checking in Python. I rarely use dictionaries anymore when what I actually want is a different type that functions will handle down the line. So to transfer data, I usually make frozen dataclasses where I used to use dictionaries. It's more work when you want to add fields on the fly ofc but it pays dividend anytime the logic becomes more complex.
Agreed -- dataclasses over dicts. And for legacy code I try to move them to typed dictionaries.

Pydantic is also helpful to enforce types on json.

I've also stopped passing around argparse namespaces. I immediately push the argparse namespace into a pydantic class (although a dataclass could also be used.)

Yes, but, the longer I use python (for personal and admin tasks mostly), the more the REPL and pytest let me sneak up on the 80% solution to my task at hand and get on with life.

The scope of possibility does not end with a full-on enterprise application, having all of the Bell() and Whistle() classes.

Even better, run `mypy` as part of your LSP setup and you don't even need to wait to run `mypy` to see type errors! If I make a mistake I want to be notified immediately.
Just use VSCode with Pylance. Much better than Mypy.
Not a VS Code user
You can use Pyright still for errors in other editors. It's better than Mypy.
I'm aware, but you said Pylance, which to my knowledge is just the VS Code extension.

I'm satisfied with Mypy but curious to someday try other type checkers. Pyright is on the list.