Clamp down on them comments!

Update (2022-09-07): Added enable_error_code = ['ignore-without-code'] to the post.

It seems inevitable that large projects need some # type: ignore comments, to work around type checking in tricky cases. I’ve found Mypy has a few options to make such ignore comments more precise and manageable.

These options are:

You can activate these flags for a whole project in pyproject.toml like so:

[tool.mypy]
enable_error_code = [
    "ignore-without-code"
]
show_error_codes = true
warn_unused_ignores = true

Let’s look at each flag in more detail.

warn_unused_ignores

This third flag helps you manage ignore comments as your code changes. When warn_unused_ignores is enabled, Mypy will log an error (not a warning) for each unnecessary ignore comment. Such redundancy can appear as your code evolves, such as when imported type hints become more accurate.

For example, imagine if you changed the previous example to remove the first line:

x: str  # type: ignore [no-redef]

Now x is only defined once. If you run Mypy with warn_unused_ignores enabled:

$ mypy --warn-unused-ignores example.py
example.py:1: error: unused 'type: ignore' comment
Found 1 error in 1 file (checked 1 source file)

…you get an error saying that you can remove the ignore comment. Neat!

Fin

May your ignorance be ever reduced,

—Adam


Learn how to make your tests run quickly in my book Speed Up Your Django Tests.


One summary email a week, no spam, I pinky promise.

Related posts:

Tags:,