EclipseでPythonのコーディングをするときに(なるべく手間暇をかけず)PEP8に準拠したい。
Eclipse+PyDevでPEP8の自動チェックと、PEP8への自動変換を有効にする方法を示す。
PyDevとは
Python用のEclipseプラグイン。
PyDev is a Python IDE for Eclipse, which may be used in Python, Jython and IronPython development.
It comes with many goodies such as:
- Django integration
 - Code completion
 - Code completion with auto import
 - Type hinting
 - Code analysis
 - Go to definition
 - Refactoring
 - Debugger
 - Remote debugger
 - Find Referrers in Debugger
 - Tokens browser
 - Interactive console
 - Unittest integration
 - Code coverage
 - Find References (Ctrl+Shift+G)
 - and many others:
 
Eclipseへのインストール方法
http://www.pydev.org/manual_101_install.html
にスクリーンショット付きでわかりやすくまとめられている。
PEP8とは
Pythonのコーディング規約。
詳細は以下を参照。
Eclipse + PyDevでのPEP8準拠チェック
PyDevはpep8とautopep8が標準で組み込まれている。
この2つでPEP8の準拠チェックとPEP8への自動変換ができる。
pep8
PEP8準拠のチェックをして、違反する箇所を出力するツール。
単体でもコマンドラインツールとして使用できる。
pep8 - Python style guide checker
pep8 is a tool to check your Python code against some of the style conventions in PEP 8.
autopep8
ソースコードをPEP8に準拠した形式に変換するツール。
PEP8準拠が簡単にできる。単体でもコマンドラインツールとして使用できる。
A tool that automatically formats Python code to conform to the PEP 8 style guide
PyDev設定
pep8を有効にする
Window -> Preferences -> PyDev -> Editor -> Code Analysis
で
OptionsタブのDo code analysis?にチェックを入れる。
pep8.pyタブのDon't run以外をチェックする。
autopep8を有効にする
Window -> Preferences -> PyDev -> Editor -> Code Style -> Code Formatter
で
Use autopep8.py for code formatting?にチェックを入れる。
保存時にautopep8を自動実行する設定
Window -> Preferences -> PyDev -> Editor -> Save Actions
で
Auto-format editor contents before saving?にチェックを入れる。
この設定をしておくと、PEP8を意識したコーディングをしていなくても
保存時にautopep8が動いてPEP8準拠のコードにしてくれる。
留意事項
autopep8を実行しただけではPEP8に完全に準拠したコードにはならない。
とはいえ大体は準拠してくれるので全てを手動で修正するよりは楽。
autopep8を走らせた後に残った箇所はpep8で警告が出るので手動で直していく。
おまけ
import 順のソート
Window -> Preferences -> PyDev -> Editor -> Save Actions
の
Sort imports on save?
にチェックを入れておくと、保存時にimportモジュールをアルファベット降順に並べかえてくれる。
これも手動でやると面倒なため、設定している。



