1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

特定の行に対してRuffとMypyの両方のチェックを無視させるには、`noqa:`より`type: ignore`を先に記述する必要がある

1
Last updated at Posted at 2026-02-16

動作確認した際の環境

  • Python 3.14.0
  • mypy 1.19.1
  • ruff 0.14.10

やりたいこと

指定した行に対して、RuffとMypyのチェックを無視するようにしたいです。

sample.py
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のチェックは無視されませんでした。

sample1.py
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の両方のチェックが無視されました。

sample2.py
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'>

参考にしたサイト

  1. https://mypy.readthedocs.io/en/stable/common_issues.html#silencing-linters

  2. https://peps.python.org/pep-0484/#type-comments

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?