一种自动格式化 Python 代码以符合 PEP 8 样式指南的工具
项目描述
autopep8 自动格式化 Python 代码以符合PEP 8样式指南。它使用pycodestyle实用程序来确定代码的哪些部分需要格式化。autopep8 能够修复 pycodestyle 报告的大多数格式 问题。
<nav class="contents" id="contents" role="doc-toc">内容
</nav>安装
从点子:
$ 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] [--hang-closing] [--exit-code]
[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:
E226,E24,W50,W690)
--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
--hang-closing hang-closing option passed to pycodestyle
--exit-code change to behavior of exit code. default behavior of
return value, 0 is no differences, 1 is error exit.
return 2 when add this option. 2 is exists
differences.
特征
autopep8 修复了pycodestyle报告的以下问题:
E101 - Reindent all lines. E11 - Fix indentation. 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. E129 - Fix visual indentation. E131 - Fix hanging indent for unaligned continuation line. E133 - Fix missing indentation for closing bracket. E20 - Remove extraneous whitespace. E211 - Remove extraneous whitespace. E22 - Fix extraneous whitespace around keywords. E224 - Remove extraneous whitespace around operator. E225 - Fix missing 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. E252 - Missing whitespace around parameter equals. E26 - Fix spacing after comment hash for inline comments. E265 - Fix spacing after comment hash for block comments. E266 - Fix too many leading '#' 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. E305 - Expected 2 blank lines after end of function or class. E306 - Expected 1 blank line before a nested definition. E401 - Put imports on separate lines. E402 - Fix module level import not at top of file 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. E713 - Use 'not in' for test for membership. E714 - Use 'is not' test for object identity. E721 - Use "isinstance()" instead of comparing types directly. E722 - Fix bare except. E731 - Use a def when use do not assign a lambda expression. 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. W503 - Fix line break before binary operator. W504 - Fix line break after binary operator. W601 - Use "in" rather than "has_key()". W602 - Fix deprecated form of raising exception. W603 - Use "!=" instead of "<>" W604 - Use "repr()" instead of backticks. W605 - Fix invalid escape sequence 'x'. W690 - Fix various deprecated code (via lib2to3).
autopep8 还修复了pycodestyle未发现的一些问题。
更正不推荐使用或非惯用的 Python 代码(通过lib2to3)。使用它来使 Python 2.7 代码与 Python 3 更兼容。(如果启用了W690 ,则会触发。)
规范化具有混合行结尾的文件。
在类文档字符串和它的第一个方法声明之间放置一个空行。(通过E301启用。)
删除函数声明与其文档字符串之间的空行。(通过E303启用。)
autopep8 避免修复pycodestyle发现的一些问题。
非注释的E112 / E113是关于破坏语法规则的错误缩进的报告。这些根本不应该被修改。
E265指的是注释散列后的间距,如果注释看起来像代码,则将被忽略。autopep8 避免修改这些,因为它们不是真正的评论。如果您真的想摆脱pycodestyle警告,请考虑删除注释掉的代码。(这可以通过 根除自动化。)
更高级的用法
默认情况下,autopep8 只进行空白更改。因此,默认情况下,它不会修复E711和E712。(如果x的__eq__方法被覆盖,将x == None更改为x is None可能会改变程序的含义。)它也不能更正弃用的代码W6。要启用这些更积极的修复,请使用--aggressive选项:
$ autopep8 --aggressive <filename>
使用多个--aggressive来增加攻击性级别。例如,E712需要 2 级攻击性(因为x == True可以更改为x或x 为 True,但 autopep8 选择前者)。
--aggressive也会更积极地缩短行。它还将更积极地删除尾随空格。(通常,我们不会触及文档字符串和其他多行字符串中的尾随空格。要对文档字符串进行更积极的更改,请使用docformatter。)
要仅启用修复的子集,请使用--select选项。例如,要修复各种类型的缩进问题:
$ autopep8 --select=E1,W1 <filename>
同样,要修复已弃用的代码:
$ autopep8 --aggressive --select=W6 <filename>
当尝试移植单个代码库以同时使用 Python 2 和 Python 3 时,上述内容很有用。
如果要修复的文件很大,您可能需要启用详细的进度消息:
$ autopep8 -v <filename>
传入 --experimental启用以下功能:
通过考虑其长度来缩短代码行
$ autopep8 --experimental <filename>
逐行禁用
可以禁用 autopep8 直到它在文件中再次打开,使用autopep8: off然后重新启用autopep8: on。
# autopep8: off
[
[23, 23, 13, 43],
[32, 34, 34, 34],
[56, 34, 34, 11],
[10, 10, 10, 10],
]
# autopep8: on
fmt: off和fmt: on也有效。
作为模块使用
使用 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'
配置
默认情况下,如果$HOME/.config/pycodestyle(在 Windows 环境中为~\.pycodestyle)存在,它将被用作全局配置文件。或者,您可以使用--global-config选项指定全局配置文件 。
另外,如果目标文件所在目录下存在setup.cfg、tox.ini、.pep8和.flake8文件,则将其作为配置文件。
pep8、pycodestyle和flake8可以用作一个部分。
配置文件示例:
[pycodestyle] max_line_length = 120 ignore = E501
pyproject.toml
autopep8 也可以使用pyproject.toml。该部分必须是[tool.autopep8],并且pyproject.toml优先于任何其他配置文件。
配置文件示例:
[tool.autopep8] max_line_length = 120 ignore = "E501,W6" # or ["E501", "W6"] in-place = true recursive = true aggressive = 3
测试
测试用例在test/test_autopep8.py中。它们可以通过 python test/test_autopep8.py或通过tox直接运行。后者对于针对多个 Python 解释器进行测试很有用。(我们目前针对 CPython 版本 2.7、3.6、3.7 和 3.8 进行测试。我们还针对 PyPy 进行测试。)
广谱测试可通过test/acid.py 获得。此脚本针对 Python 代码运行 autopep8 并检查代码修复的正确性和完整性。它可以检查字节码是否保持相同。 test/acid_pypi.py使用acid.py来测试 PyPI 上最新发布的包。
故障排除
pkg_resources.DistributionNotFound
如果您使用的是旧版本的setuptools ,则在尝试运行 autopep8 时可能会遇到 pkg_resources.DistributionNotFound。尝试升级setuptools以解决此setuptools问题:
$ pip install --upgrade setuptools
如果要安装到系统,请使用sudo 。