1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Python] 特定の警告だけを無視したい(VSCode)

Last updated at Posted at 2025-01-31

Pythonでコードを書いているとき、特定の警告を無視したい… って感じるときありませんか?

たとえば、こんな時とか…

import re

qwe123rty = "qwe123rty"

num = re.search(r"(\d+)", qwe123rty)[0]


文字列の中に数字が含まれてるのは明らかなんだし、ただうるさいだけです。

これだけのためにNoneチェックをするのは大げさですし…。

found = re.search(r"(\d+)", qwe123rty)
if found:
    num = found[0]
else:
    raise Exception("どうせ例外出すんだから結局同じこと")
found = re.search(r"(\d+)", qwe123rty)
assert found is not None  # 多少短く書ける
num = found[0]

(文字列に手を加える可能性があるなど、丁寧にNoneチェックをした方が良い場合もあります)

環境

  • Python 3.11.9
  • VSCode 1.96.4
    • Pylance 2024.12.1

普通の環境です。VSCodeでPythonを使うなら通常はPylanceでしょう。

# type: ignore ではダメ

# type: ignore を突っ込めば赤波線を問答無用で非表示にすることはできますが…
これでは、関係ない警告も巻き添えで非表示にしてしまいます。

import re

qwe123rty = "qwe123rty"

num1 = re.search(r"(\d+)", qwe123rty)[0]  # type: ignore
num2 = re.search(r"(\d+)", str(1 / None)())[0]  # type: ignore
#                          ^^^^^^^^^^^^^^^ エラーの塊

あきらかにエラー詰め合わせなのに警告が消えてる!
これは大問題です。1行とはいえ、とても危険です。

# type: ignore では細かいフィルタリングなどはできないため、別の方法でignoreをする必要があります。

# pyright: ignore[~~] を使う

# pyright: ignore[~~] の記法でignoreすることで、特定の警告のみを無視する ことが可能になります。

~~ の中身は、VSCodeのホバー表示や問題ペインで確認できる Pylance(reportOptionalSubscript) の文字列を入れます。

import re

qwe123rty = "qwe123rty"

num1 = re.search(r"(\d+)", qwe123rty)[0]  # pyright: ignore[reportOptionalSubscript]
num2 = re.search(r"(\d+)", str(1 / None)())[0]  # pyright: ignore[reportOptionalSubscript]
#                          ^^^^^^^^^^^^^^^ エラーの塊

re.searchだけエラーが消えていることが確認できます。
消したかった「"None" 型のオブジェクトは添字可能ではありません」の警告のみが消えていて、ほかの警告は残っていることも確認できます。

これで、鬱陶しい警告だけを非表示にすることができる…!!

注意点:Pyrightのみです

見るからにそんな感じがしますが、Pyrightによる型チェックが働いている環境でしか効きません。
(Pylanceは内部でPyrightを使っています)

mypyでこれをやりたい場合は、以下のようにするそうです。
(環境によっては--enable-error-codeの指定が必要とのこと)

# 'foo' is defined in 'foolib', even though mypy can't see the
# definition.
from foolib import foo  # type: ignore[attr-defined]

# type: ignoreの後にエラーコードを追加するんだそうな。
直感的でいいですね!

もちろんPyrightとエラーコードは共有していないので、mypyに対応する場合はPyrightを捨てる必要があります。
# type: ignore で全部まとめて捨てるよりかはマシでしょう。

まとめ

# type: ignore は危険

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?