delhi09の勉強日記

技術トピック専用のブログです。自分用のメモ書きの投稿が多いです。あくまで「勉強日記」なので記事の内容は鵜呑みにしないでください。

mypyの使い方

mypyを使ってPythonで型チェックする方法について書く。

mypyとは

Pythonの型チェッカー。チェックのみで変更はしない。

mypyのコマンドラインからの使い方

・インストール方法

$ pip install mypy

・実行方法(ファイル単位)

$ mypy target_file.py

・実行方法(ディレクトリ配下全て)

$ mypy target_dir

※ 注意

実際にはディレクトリを指定した場合、ディレクトリ配下1階層のファイルまでしか探索されない。 (2020/4/29、mypyのversion 0.770 時点)


例えば、以下のようなディレクトリに対して

$ tree sample
sample/
├── hello.py
└── tmp
    └── hello2.py
$ mypy sample

を実行すると、「hello.py」にはmypyが実行されるが、hello2.pyには実行されない。

$ mypy sample
Success: no issues found in 1 source file

上記の事象に関しては、Guido van Rossum

I think it’s actually a bug that when you specify a directory on the command line it doesn’t really recurse into that directory, but does a shallow directory listing.

I propose to fix that bug and replace the shallow directory listing with a proper walking of the directory hierarchy starting at that point.

と以下のisuueでコメントしているので、後のバージョンでrecursiveに実行されるように修正されるのだろう。
github.com


・実行例1(チェック箇所が存在する場合)

以下のファイルにmypyを実行する。
(戻り値にstr型が指定されているがint型を返している。)

[hello.py]

def hello(name: str) -> str:
    print(f'Hello {name}!')
    return 1

hello('Mike')

実行結果

$ mypy hello.py
hello.py:3: error: Incompatible return value type (got "int", expected "str")
Found 1 error in 1 file (checked 1 source file)


・実行例2(チェック箇所が存在しない場合)

以下のファイルにmypyを実行する。
(戻り値をstr型に修正した)

[hello.py]

def hello(name: str) -> str:
    return f'Hello {name}!'

hello('Mike')

実行結果

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


・実行例3(型を使用していない場合)

以下のファイルにmypyを実行する。

[hello.py]

def hello(name):
    return f'Hello {name}!'

hello('Mike')

実行結果

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

型を使用していない場合はパスする。