python

今回はflake8, autopep8を使って、Pythonコードを静的解析します。

静的解析とは

コードを実行せずに行う解析です。コーディングルールチェックや、制御フローの解析、コードの複雑度の分析をすることでソースコードにある問題点を発見してくれます。

flake8とは

pep8のチェック、pyflakesのチェック、及び循環的複雑度をチェックできるラッパーのことです。導入をすることで普段から綺麗なコーディングができます。

autopep8とは

pep8のスタイルガイドに適用するように、自動的にPythonコードをフォーマットしてくれます。

flake8, autopep8インストール

さっそくインストールしていきましょう。
以下コマンドでflake8をインストールできます。

pip install flake8

次にautopep8をインストールします。

pip install autopep8

とても簡単ですね。

使い方

flake8

flake8 <対象ファイルへのパス>

このコマンドで対象ファイルを静的解析することができ、結果をターミナルに表示してくれます。

autopep8

autopep8 --in-place --aggressive --aggressive <filename>

公式ドキュメントにはこのように実行することを推奨しています。 --in--placeをつけることでファイルを更新してくれます。これがないとコードを自動的にフォーマットして、更新してくれません。 --aggressiveをつけることでコード整形のレベルを指定でき、2つつけることでレベル2になり修正対象のエラーが増えるそうです。 このコマンドで対象ファイルを静的解析することができ、結果をターミナルに表示してくれます。

試してみる

test.pyを任意のディレクトリに作成します。 内容はこんな感じにしてみました。

def example(num_a,num_b,num_c,num_d,num_e,num_f,num_g,num_h):
    print(num_a+num_b+num_c+num_d+num_e+num_f+num_g+num_h)
num_a,num_b,num_c,num_d,num_e,num_f,num_g,num_h = 1,   2,  3,  4, 5,  6,  7,   8
example(   num_a,     num_b,      num_c, num_d,num_e,   num_f,  num_g,   num_h  )

適切な改行や空白をいれることができていないし、文字列がとても長くなってしまっています。まずはflake8で静的解析をします。

test.py:1:18: E231 missing whitespace after ','
test.py:1:24: E231 missing whitespace after ','
test.py:1:30: E231 missing whitespace after ','
test.py:1:36: E231 missing whitespace after ','
test.py:1:42: E231 missing whitespace after ','
test.py:1:48: E231 missing whitespace after ','
test.py:1:54: E231 missing whitespace after ','
test.py:3:1: E305 expected 2 blank lines after class or function definition, found 0
test.py:3:6: E231 missing whitespace after ','
test.py:3:12: E231 missing whitespace after ','
test.py:3:18: E231 missing whitespace after ','
test.py:3:24: E231 missing whitespace after ','
test.py:3:30: E231 missing whitespace after ','
test.py:3:36: E231 missing whitespace after ','
test.py:3:42: E231 missing whitespace after ','
test.py:3:80: E501 line too long (80 > 79 characters)
test.py:4:9: E201 whitespace after '('
test.py:4:47: E231 missing whitespace after ','
test.py:4:80: E501 line too long (81 > 79 characters)
test.py:4:80: E202 whitespace before ')'

コードが汚いと怒られていますね。この汚いコードを綺麗にするために、autopep8を実行します。 その後、ソースコードを見ると

def example(num_a, num_b, num_c, num_d, num_e, num_f, num_g, num_h):
    print(num_a + num_b + num_c + num_d + num_e + num_f + num_g + num_h)


num_a, num_b, num_c, num_d, num_e, num_f, num_g, num_h = 1, 2, 3, 4, 5, 6, 7, 8
example(num_a, num_b, num_c, num_d, num_e, num_f, num_g, num_h)

いい感じにコードをフォーマットしてくれてますね!!

flake8, autopep8は導入するのが簡単ですし、静的解析を常日頃から意識して開発ができるとチームメンバーがコードを理解しやすくなったりするので、是非取り入れてください。