🎉

Mypyとそれ以外のリンターを比較してみる。

2025/01/27に公開

Pythonのtype checkerとしてMypyを利用する事は多いと思いますが、その他リンターとの関係性を調査してみました。

サンプルコード

from typing import NewType

UserId = NewType('UserId', int)

def get_user_name(user_id: UserId):# ① Rerun Typeが存在しない。
    return f"User: {user_id}"

def main() -> None:
    id = UserId(1)
    user_name=get_user_name(id)
    print(user_name + 1) # ② str型をインクリメンとしている。

if __name__ == "__main__":
    main()

Mypy

mypyコマンドのみの実施ではエラーは検知されない。

$ mypy test.py         
Success: no issues found in 1 source file

Mypy strict mode

① Rerun Typeが存在しない部分のみを検知

$ mypy --strict  test.py
test.py:5: error: Function is missing a return type annotation  [no-untyped-def]
Found 1 error in 1 file (checked 1 source file)

pyre

はエラーは検知されない。

$ pyre
ƛ No type errors found

Pyright

② str型をインクリメンとしている部分でエラー検知している。

Pyright test.py
/Users/takeshiiijima/Desktop/test/test.py
  /Users/takeshiiijima/Desktop/test/test.py:11:11 - error: Operator "+" not supported for types "str" and "Literal[1]" (reportOperatorIssue)
1 error, 0 warnings, 0 informations

Pytype

② str型をインクリメンとしている部分でエラー検知している。

pytype test.py       
Computing dependencies
Analyzing 1 sources with 0 local dependencies
ninja: Entering directory `.pytype'
[1/1] check test
FAILED: /Users/takeshiiijima/Desktop/test/.pytype/pyi/test.pyi 
/Users/takeshiiijima/Library/Caches/pypoetry/virtualenvs/test-XsGIjM_l-py3.10/bin/python -m pytype.main --imports_info /Users/takeshiiijima/Desktop/test/.pytype/imports/test.imports --module-name test --platform darwin -V 3.10 -o /Users/takeshiiijima/Desktop/test/.pytype/pyi/test.pyi --analyze-annotated --nofail --quick /Users/takeshiiijima/Desktop/test/test.py
/Users/takeshiiijima/Desktop/test/test.py:11:1: error: in main: unsupported operand type(s) for +: str and int [unsupported-operands]
  Function __add__ on str expects str

    print(user_name + 1)~~~~~~~~~~~~~~~~~~~~~~~
    print(user_name + 1)



For more details, see https://google.github.io/pytype/errors.html#unsupported-operands
ninja: build stopped: subcommand failed.
Leaving directory '.pytype'

まとめ

mypy(strict mode)により厳密な型チェックが可能だと思います。
しかし、途中から型チェックを導入する場合や型が十分に設定されていないプロジェクトはありそうです。mypyの完成を最終的なゴールにしながら、補助としてPytypeやPyrightを利用する方針が良いように感じます。

Discussion