pytype:型ヒントなしでも使えるPython用静的型検証ツール

github.com

PytypeはGoogle製のPython用静的型検証ツールです。型ヒントなしのコードでも型推論を行って検証し、潜在的なバグを指摘してくれます。

インストール

pip install pytype

使用例

例えば以下のようなfoo.pyというファイルがあったとします。

def increment(x):
    return x + 1

increment('0')

このコードは実行するとTypeErrorをraiseします。

pytypeでこのコードを検証してみます。

$ pytype foo.py

すると、以下の通り当該コードに対してunsupported operand type(s) for +: 'str' and 'int'というエラーを出力します。実引数と関数本体のコードを組み合わせた検証もしてくれることが分かります。

File "/Users/mickey/depot/pytype_examples/foo.py", line 2, in increment: unsupported operand type(s) for +: 'str' and 'int' [unsupported-operands]
  Function __add__ on str expects str
Called from (traceback):
  line 4, in current file

pytypeは型推論以外にも、未定義属性の参照など様々なプログラムエラーをレポートしてくれます。

class Person(object):
    def __init__(self, name):
        self.name = name
        # self.ageを定義していない

    def greet(self):
        # 未定義のself.ageを参照している
        print("Hi, I'm {}. I'm {} years old.".format(self.name, self.age))
$ pytype foo.py
File "/Users/mickey/depot/pytype_examples/foo.py", line 8, in greet: No attribute 'age' on Person [attribute-error]

その他の使い方はGithubのプロジェクトページを参照してください。例えば、pytypeが解析した型情報を型ヒントとして出力し、ソースコードにmergeすることも可能です。

まとめ

pytypeは型ヒントなしのコードでも型推論を行い検証してくれます。実際にコードを実行する前に潜在的なバグを素早く確認できるため、ユニットテストの前に実行させるようにしておくと便利です。