Hacker News new | ask | show | jobs
by nas 1521 days ago
I've found that it's pretty easy to slowly enable mypy checking. You can mark modules with "type:ignore" to make mypy ignore them. Then, you can move to marking individual statements with "type:ignore". Finally, you can start marking modules with "mypy: disallow-any-generics" at the top. That requires that functions are annotated with types.

In a large code base, our team has found type annotations and mypy to be quite helpful. If you are writing a quick-and-dirty script, forget about wasting time with type annotations. However, for long-lived and important code, it seems to be worth adding the types.

Another thing I noticed, if your type annotations are hard to write, e.g. lots "Union", "Optional" or deeply nested type expressions, it's probably a sign that your code is poorly designed. Think about what types you actually want to consume and return. Define new containers using dataclasses or attrs to keep the types simple, if required.

3 comments

Right - I mean we had mypy passing across the whole project, but it just wasn't detecting any issues because so many of our types had to be ignored because mypy didn't understand that the runtime type of a Column field in SQLAlchemy is not Column, and things like that.

Rather than maintain all of the mypy stubs for no benefit, we decided to just scrap mypy.

> You can mark modules with "type:ignore" to make mypy ignore them.

If I added MyPy to the CI/CD checks, some coworkers would flood the code with these to not have to think about their typing. Too bad that some libraries like SQLAlchemy make this mandatory sometimes. I'd like the option to ignore these "type:ignore", but the type system is too immature and has to be overridden sometimes.

I disagree with your last line, especially for Optional (Union in python is basically useless IMO).
Isn't `Optional[T]` just sugar for `Union[T, None]`?
Touché. I guess a common pattern I find myself doing for Union types is having if statements checking if something is of a type using reflection. When checking if it is none, it is more elegant.