Python の mypy でエラーを一行だけ無視する
2022-10-29


mypy は Python の静的アナライザ。

少し厳し目の判別をしてくれるが、目に付きづらいバグなどを検出できるので、有効にしている。

しかし、時折り融通が効かず、一行だけ無効にする必要があったりする。個人的に問題が出るのは、関数の引数などで複数の型を受け取れる様にした時等に問題になる。

例えば、int 型と list[int] 型のどちらでも受けると、list[int] 型に統一して処理したいのだが、そこでエラーを出されてしまう。

次のは、union[None, int, list[int]] 型の時のエラーの例。

def func(ids: Union[None, int, List[int]]):
    if type(ids) == int:
        ids = [ids]
少し書き換えてちょこちょこ試行錯誤していると、「List item 0 has incompatible type "Union[int, List[int]]"; expected "int"」や「Argument 1 to "int" has incompatible type "Union[int, List[int]]"; expected "Union[str, bytes, SupportsInt, SupportsIndex, SupportsTrunc]"」等が出てくる。

以下の様にして特定の行のみで無効にして対処する。

ids = [ids] # type: ignore
[Programming]
[python]

コメント(全0件)
コメントをする


記事を書く
powered by ASAHIネット