LoginSignup
12
15

More than 5 years have passed since last update.

Eclipse+PyDevでPythonコーディング規約(PEP8)を準拠するための環境構築

Last updated at Posted at 2016-01-02

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準拠が簡単にできる。単体でもコマンドラインツールとして使用できる。

https://pypi.python.org/pypi/autopep8Use

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?にチェックを入れる。

code_analysis_pep8_01.png

pep8.pyタブのDon't run以外をチェックする。

code_analysis_pep8_02.png

autopep8を有効にする

Window -> Preferences -> PyDev -> Editor -> Code Style -> Code Formatter

Use autopep8.py for code formatting?にチェックを入れる。

code_formatter.png

保存時にautopep8を自動実行する設定

Window -> Preferences -> PyDev -> Editor -> Save Actions

Auto-format editor contents before saving?にチェックを入れる。

auto_format.png

この設定をしておくと、PEP8を意識したコーディングをしていなくても
保存時にautopep8が動いてPEP8準拠のコードにしてくれる。

留意事項

autopep8を実行しただけではPEP8に完全に準拠したコードにはならない。
とはいえ大体は準拠してくれるので全てを手動で修正するよりは楽。
autopep8を走らせた後に残った箇所はpep8で警告が出るので手動で直していく。

おまけ

import 順のソート

Window -> Preferences -> PyDev -> Editor -> Save Actions

Sort imports on save?
にチェックを入れておくと、保存時にimportモジュールをアルファベット降順に並べかえてくれる。
これも手動でやると面倒なため、設定している。

12
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
15