動作確認した際の環境
- Python 3.14.0
- mypy 1.19.1
- ruff 0.14.10
やりたいこと
指定した行に対して、RuffとMypyのチェックを無視するようにしたいです。
foo = 1
foo = "abcdefghijklmnopqrstuvwxyz"
$ mypy sample.py
sample.py:2: error: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
Found 1 error in 1 file (checked 1 source file)
$ ruff check --select E501 --line-length 30
E501 Line too long (34 > 30)
--> sample.py:2:31
|
1 | foo = 1
2 | foo = "abcdefghijklmnopqrstuvwxyz"
| ^^^^
|
Found 1 error.
試したこと
行末コメントに無視するディレクティブを、noqa:、type:の順番に記載しました。
Ruffのチェックは無視されましたが、Mypyのチェックは無視されませんでした。
foo = 1
foo = "abcdefghijklmnopqrstuvwxyz" # noqa: E501 # type: ignore[assignment]
$ mypy sample1.py
sample1.py:2: error: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
Found 1 error in 1 file (checked 1 source file)
$ ruff check --select E501 --line-length 30 sample1.py
All checks passed!
一方、行末コメントに無視するディレクティブを、type:、noqa:の順番に記載したところ、RuffとMypyの両方のチェックが無視されました。
foo = 1
foo = "abcdefghijklmnopqrstuvwxyz" # type: ignore[assignment] # noqa: E501
$ mypy sample2.py
Success: no issues found in 1 source file
$ ruff check --select E501 --line-length 30 sample2.py
All checks passed!
公式ドキュメントおよびPEPでの記載
type:、noqa:の順番に記載しないといけない旨は、公式ドキュメントに記載されていました。
To silence the linter on the same line as a type comment put the linter comment after the type comment: 1
また、PEP 484にも記載されていました。
In some cases, linting tools or other comments may be needed on the same line as a type comment. In these cases, the type comment should be before other comments and linting markers: 2
Mypyではどのように処理しているか
parse_type_comment関数の以下のコードで、type: ignoreコメントを正規表現で検索しています。
実際にコードを実行して、期待通りの結果であることを確認しました。
In [3]: TYPE_IGNORE_PATTERN = re.compile(r"[^#]*#\s*type:\s*ignore\s*(.*)")
In [9]: TYPE_IGNORE_PATTERN.match("# noqa: E501 # type: ignore[assignment]")
In [10]: TYPE_IGNORE_PATTERN.match("# type: ignore[assignment] # noqa: E501")
Out[10]: <re.Match object; span=(0, 40), match='# type: ignore[assignment] # noqa: E501'>
参考にしたサイト