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:
show_error_codes
, which tells Mypy to identify error messages with their codes, which you can then use in ignore comments. This on by default from Mypy 0.900.enable_error_code = ['ignore-without-code']
, which tells Mypy that all ignore comments need specific error codes.warn_unused_ignores
, which tells Mypy to log errors for unnecessary ignore comments.
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:
- Python type hints: Mypy doesn’t allow variables to change type
- Python type hints: upgrade syntax with pyupgrade
- Python type hints: use Mypy’s unreachable code detection
Tags:,