Github: https://github.com/hhatto/autopep8
autopep8
autopep8は自動的にPEP 8スタイルガイドに適合するようにPythonコードをフォーマットします。 pycodestyleユーティリティを使用して、コードのどの部分をフォーマットする必要があるかを判断します。 autopep8は、pycodestyleによって報告されるほとんどの書式設定の問題を修正することができます。
インストール
ピップから:
$ pip install --upgrade autopep8
--user
オプションの使用を検討してください。
要件
autopep8にはpycodestyleが必要です 。
使用法
適切な場所にファイルを変更するには(積極的なレベル2で):
$ autopep8 --in-place --aggressive --aggressive <filename>
autopep8を実行する前に
import math, sys;
def example1():
####This is a long comment. This should be wrapped to fit within 72 characters.
some_tuple=( 1,2, 3,'a' );
some_variable={'long':'Long code lines should be wrapped within 79 characters.',
'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
20,300,40000,500000000,60000000000000000]}}
return (some_tuple, some_variable)
def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key(''));
class Example3( object ):
def __init__ ( self, bar ):
#Comments should have a space after the hash.
if bar : bar+=1; bar=bar* bar ; return bar
else:
some_string = """
Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
return (sys.path, some_string)
autopep8を実行した後。
import math
import sys
def example1():
# This is a long comment. This should be wrapped to fit within 72
# characters.
some_tuple = (1, 2, 3, 'a')
some_variable = {
'long': 'Long code lines should be wrapped within 79 characters.',
'other': [
math.pi,
100,
200,
300,
9876543210,
'This is a long string that goes on'],
'more': {
'inner': 'This whole logical line should be wrapped.',
some_tuple: [
1,
20,
300,
40000,
500000000,
60000000000000000]}}
return (some_tuple, some_variable)
def example2(): return ('' in {'f': 2}) in {'has_key() is deprecated': True}
class Example3(object):
def __init__(self, bar):
# Comments should have a space after the hash.
if bar:
bar += 1
bar = bar * bar
return bar
else:
some_string = """
Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
return (sys.path, some_string)
オプション:
usage: autopep8 [-h] [--version] [-v] [-d] [-i] [--global-config filename] [--ignore-local-config] [-r] [-j n] [-p n] [-a] [--experimental] [--exclude globs] [--list-fixes] [--ignore errors] [--select errors] [--max-line-length n] [--line-range line line] [files [files ...]] Automatically formats Python code to conform to the PEP 8 style guide. positional arguments: files files to format or '-' for standard in optional arguments: -h, --help show this help message and exit --version show program's version number and exit -v, --verbose print verbose messages; multiple -v result in more verbose messages -d, --diff print the diff for the fixed source -i, --in-place make changes to files in place --global-config filename path to a global pep8 config file; if this file does not exist then this is ignored (default: ~/.config/pep8) --ignore-local-config don't look for and apply local config files; if not passed, defaults are updated with any config files in the project's root directory -r, --recursive run recursively over directories; must be used with --in-place or --diff -j n, --jobs n number of parallel jobs; match CPU count if value is less than 1 -p n, --pep8-passes n maximum number of additional pep8 passes (default: infinite) -a, --aggressive enable non-whitespace changes; multiple -a result in more aggressive changes --experimental enable experimental fixes --exclude globs exclude file/directory names that match these comma- separated globs --list-fixes list codes for fixes; used by --ignore and --select --ignore errors do not fix these errors/warnings (default: E24) --select errors fix only these errors/warnings (e.g. E4,W) --max-line-length n set maximum allowed line length (default: 79) --line-range line line, --range line line only fix errors found within this inclusive range of line numbers (e.g. 1 99); line numbers are indexed at 1
特徴
autopep8はpycodestyleによって報告された以下の問題を修正しています:
E101 - Reindent all lines. E11 - Fix indentation. (not include E112 and E113) E121 - Fix indentation to be a multiple of four. E122 - Add absent indentation for hanging indentation. E123 - Align closing bracket to match opening bracket. E124 - Align closing bracket to match visual indentation. E125 - Indent to distinguish line from next logical line. E126 - Fix over-indented hanging indentation. E127 - Fix visual indentation. E128 - Fix visual indentation. E20 - Remove extraneous whitespace. E211 - Remove extraneous whitespace. E22 - Fix extraneous whitespace around keywords. E224 - Remove extraneous whitespace around operator. E226 - Fix missing whitespace around arithmetic operator. E227 - Fix missing whitespace around bitwise/shift operator. E228 - Fix missing whitespace around modulo operator. E231 - Add missing whitespace. E241 - Fix extraneous whitespace around keywords. E242 - Remove extraneous whitespace around operator. E251 - Remove whitespace around parameter '=' sign. E26 - Fix spacing after comment hash for inline comments. E265 - Fix spacing after comment hash for block comments. E27 - Fix extraneous whitespace around keywords. E301 - Add missing blank line. E302 - Add missing 2 blank lines. E303 - Remove extra blank lines. E304 - Remove blank line following function decorator. E306 - Expected 1 blank line before a nested definition E401 - Put imports on separate lines. E501 - Try to make lines fit within --max-line-length characters. E502 - Remove extraneous escape of newline. E701 - Put colon-separated compound statement on separate lines. E70 - Put semicolon-separated compound statement on separate lines. E711 - Fix comparison with None. E712 - Fix comparison with boolean. E721 - Use "isinstance()" instead of comparing types directly. E722 - Fix bare except. W291 - Remove trailing whitespace. W292 - Add a single newline at the end of the file. W293 - Remove trailing whitespace on blank line. W391 - Remove trailing blank lines. W601 - Use "in" rather than "has_key()". W602 - Fix deprecated form of raising exception. W603 - Use "!=" instead of "<>" W604 - Use "repr()" instead of backticks. W690 - Fix various deprecated code (via lib2to3).
autopep8はpycodestyleで見つからない問題も修正しました。
- 非難や非慣用的なPythonコードを
lib2to3
(lib2to3
経由)。 Python 2.7コードをPython 3との互換性を高めるために使用します(W690
が有効な場合にW690
ます)。 - 行末が混在するファイルを正規化します。
- クラスdocstringとその最初のメソッド宣言の間に空白行を置きます。 (
E301
有効) - 関数宣言とそのドキュメントストリングの間の空白行を削除します。 (
E303
有効)
autopep8は、 pycodestyleによって発見されたいくつかの問題の修正を避けます。
- 非コメントの
E112
/E113
、構文規則を破るインデントの悪い報告です。 これらはまったく変更すべきではありません。 - コメントハッシュ後のスペースを参照する
E265
は、コメントがコードのように見える場合は無視されます。 autopep8は実際のコメントではないので、これらの変更を避けます。 本当にpycodestyle警告を取り除きたいのであれば、コメントアウトされたコードを削除するだけでよいでしょう。 (これは根絶を介して自動化することができます)。
より高度な使い方
デフォルトでは、autopep8は空白を変更するだけです。 したがって、デフォルトでは、 E711
とE712
は修正されません。 ( x == None
をx is None
変更すると、 x
が__eq__
メソッドをオーバーライドしても、 x
x is None
はプログラムの意味を変更する可能性があります)また、廃止予定のコードW6
も修正しません。 これらのより積極的な修正を有効にするには、 – --aggressive
オプションを使用します。
$ autopep8 --aggressive <filename>
アグレッシブレベルを上げるには、複数の--aggressive
を使用します。 たとえば、 E712
では積極性レベル2が必要です( x == True
はx
またはx is True
変更できますが、 x is True
ですが、autopep8はこれを選択します)。
--aggressive
はまた、より積極的に行を短縮します。 後ろの空白をより積極的に削除します。 (通常は、 ドキュメントストリングやその他のマルチライン文字列の末尾にある空白には触れません。また、 ドキュメントストリングの変更をもっと積極的に行うには、 docformatterを使用してください )。
修正のサブセットのみを有効にするには、 --select
オプションを使用します。 たとえば、さまざまなタイプのインデント問題を修正するには:
$ autopep8 --select=E1,W1 <filename>
同様に、廃止予定のコードを修正するだけです:
$ autopep8 --aggressive --select=W6 <filename>
上記は、Python 2とPython 3の両方で同時に動作するように単一のコードベースを移植しようとする場合に便利です。
修正されるファイルが大きい場合は、詳細な進行メッセージを有効にすることができます。
$ autopep8 -v <filename>
モジュールとして使用する
autopep8をモジュールとして使用する最も簡単な方法は、 fix_code()
関数を使用する方法です。
>>> import autopep8 >>> autopep8.fix_code('x= 123\n') 'x = 123\n'
またはオプション付き:
>>> import autopep8 >>> autopep8.fix_code('x.has_key(y)\n', ... options={'aggressive': 1}) 'y in x\n' >>> autopep8.fix_code('print( 123 )\n', ... options={'ignore': ['E']}) 'print( 123 )\n'
テスト
テストケースはtest/test_autopep8.py
ます。 それらはpython test/test_autopep8.py
またはpython test/test_autopep8.py
を介して直接実行できます。 後者は、複数のPythonインタプリタをテストするのに便利です。 (私たちは現在、CPythonバージョン2.7,3.4,3.5、および3.6に対してテストしています.PyPyもテストしています)。
幅広いスペクトルテストは、 test/acid.py
から利用できます。 このスクリプトは、Pythonコードに対してautopep8を実行し、コード修正の正確さと完全性をチェックします。 バイトコードが同一であることを確認できます。 test/acid_pypi.py
はtest/acid_pypi.py
を使ってPyPI上で最新のリリースパッケージをテストします。
トラブルシューティング
pkg_resources.DistributionNotFound
古いバージョンのsetuptools
を使用している場合は、 pkg_resources.DistributionNotFound
を実行しようとするとpkg_resources.DistributionNotFound
が発生する可能性があります。 このsetuptools
問題を回避するためにsetuptools
をアップグレードしてみてください:
$ pip install --upgrade setuptools
システムにインストールする場合は、 sudo
使用してください。