中野智文のブログ

データ・マエショリストのメモ

Jupyter notebook (Python3) で mypy のチェックを行う

背景

python3 で導入された型ヒントだが、そのままだと静的にも動的にもアノテーション(単なるコメント)として扱われるらしく、ちょっと残念。 mypy というコマンドで型チェックを行ってくれるらしい。Jupyter notebook 上でも実行したい。

対応

mypy をインストールする。

pip install mypy

typecheck.py をダウンロード

ipython の profile ディレクトリの start up で typecheck.py をダウンロード

cd ~/.ipython/profile_default/startup
curl https://gist.githubusercontent.com/knowsuchagency/f7b2203dd613756a45f816d6809f01a6/raw/c9c1b7ad9fa25a57ee1903d755d5525894ffa411/typecheck.py -o typecheck.py

最新版?は、 A cell magic to enable the use of mypy within jupyter notebooks · GitHub で確認すること

カーネルの再起動

jupyter notebook の再起動でもいいけど、あのリロードボタン。

magics を評価したいセルに埋め込む

次の magics を使いたいセルの先頭に埋め込む

以下は例:

%%typecheck --ignore-missing-imports

foo: int

foo = 'var'

すると、<string>:5: error: Incompatible types in assignment (expression has type "str", variable has type "int") とエラー(警告)が表示される。 これが見たかった。

まとめ

あまり jupyter で使っている例を見ないけど、mypy は jupyter notebook で使える。

追記

残念なことに magics はセルごとに起動するので、別のセルの型ヒントや別のセルの typing から import した型は見えてないかもしれない(というか magics の仕組み上恐らく見えていないだろう)。 セルごとに毎度 import したり、まとめられるセルはまとめてしまうなどの工夫が必要。

参考

journalpanic.com