LoginSignup
0
0

Python静的型チェックツール(mypy)

Posted at

Pythonで静的型チェックを行う

本記事では型ヒントの静的型チェックツールであるmypyについて記載する。

mypyとは

Pythonコードの静的型チェックを行うツール。
Pythonは動的型付け言語のため、型ヒントの利用に不整合があっても、プログラム実行時にはエラーとならない。そのため、無理に使用する必要はないが、静的型チェックツールと併せて利用することで不整合のない綺麗なコードを記述できる。

  • mypyのインストール
$ pip install mypy

mypyによる静的型チェック

早速mypyを利用してエラーを出力する。
下記コマンドを実行して確認する。

$ mypy 'ファイル名'
エラーメッセージ
エラーメッセージ 説明
Incompatible types in assignment 変数の型と異なる型の値を代入している
Incompatible return value type 戻り値の型と異なる型の値を返している
Argument 1 to "test1" has incompatible type "int"; expected "str" 引数の型と異なる型の値を渡している
  • 変数の型チェック

ファイルを作成し、下記コードを記述する。

name: str = 1234
age: int = '18'
favorite: list = {"study": "プラグラム", "food": "ラーメン", "sports": "陸上"}
size: dict = [168.0, 77.0, 63.5]

コマンドを実行し、出力結果を確認する。

<出力結果>
mypy_test.py:1: error: Incompatible types in assignment (expression has type "int", variable has type "str")  [assignment]
mypy_test.py:2: error: Incompatible types in assignment (expression has type "str", variable has type "int")  [assignment]
mypy_test.py:3: error: Incompatible types in assignment (expression has type "dict[str, str]", variable has type "list[Any]")  [assignment]   
mypy_test.py:4: error: Incompatible types in assignment (expression has type "list[float]", variable has type "dict[Any, Any]")  [assignment] 
Found 4 errors in 1 file (checked 1 source file)
  • 関数の型チェック

下記コードを記述する。

def test1(msg: str) -> int:
    return msg


print(test1(123))

コマンドを実行し、出力結果を確認する。

<出力結果>
mypy_test2.py:2: error: Incompatible return value type (got "str", expected "int")  [return-value]
mypy_test2.py:5: error: Argument 1 to "test1" has incompatible type "int"; expected "str"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

オプション一覧

オプション 説明
disallow_any_generics コンテナ(listやdictなど)の要素の型がないことを禁止する
disallow_untyped_defs 型がない関数定義を禁止する
disallow_untyped_calls 型がない関数呼び出しを禁止する
warn_unused_ignore 静的型チェックの対象外とするためのコメント「# type: ignore」がある場合に警告メッセージを表示する
warn_return_any 型がない変数を返す場合に警告メッセージを表示する
check_untyped_defs 型がない関数内部の型をチェックする
follow_imports インポートしたモジュールをチェックするルールを指定する
ignore_missing_imports インポートしたモジュールに関するエラーを抑制する
exclude 除外するファイルやディレクトリを正規表現で指定する
0
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
0
0