跳转到主要内容

一个自动格式化Python代码以符合PEP 8风格指南的工具

项目描述

PyPI Version Build status Code Coverage

autopep8自动将Python代码格式化以符合PEP 8风格指南。它使用pycodestyle实用程序来确定哪些代码部分需要格式化。autopep8可以修复大多数pycodestyle可以报告的格式化问题

安装

来自pip

$ pip install --upgrade autopep8

考虑使用 --user 选项。[链接](https://pip.pythonlang.cn/en/latest/user_guide/#user-installs)

需求

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.
W605 - Fix invalid escape sequence 'x'.

autopep8 还修复了 pycodestyle 未发现的一些问题。

  • 统一具有混合行结束的文件。

  • 在类的文档字符串和其第一个方法声明之间放置一个空行。(通过 E301 启用。)

  • 在函数声明和其文档字符串之间删除空白行。(通过 E303 启用。)

autopep8 避免修复由 pycodestyle 发现的一些问题。

  • E112/E113 对于非注释是破坏语法规则的错误缩进的报告。这些不应该做任何修改。

  • E265,它指的是注释符号后的间距,如果注释看起来像代码,则会被忽略。autopep8 避免修改这些,因为它们不是真正的注释。如果您真的想消除 pycodestyle 警告,考虑仅删除已注释掉的代码。(这可以通过 eradicate 自动化。)

更高级的用法

默认情况下,autopep8 只进行空白更改。因此,默认情况下,它不修复 E711E712。(将 x == None 更改为 x is None 可能会改变程序的含义,如果 x 覆盖了其 __eq__ 方法。)它也不会修复已弃用的代码 W6。要启用这些更激进的修复,请使用 --aggressive 选项

$ autopep8 --aggressive <filename>

使用多个 --aggressive 来增加激进度。例如,E712 需要2级激进度(因为 x == True 可以改为 xx is True,但autopep8选择前者)。

--aggressive 也会更激进地缩短行。它还将更激进地删除尾随空格。(通常,我们不触摸文档字符串和其他多行字符串中的尾随空格。要执行对文档字符串的更激进更改,请使用 docformatter。)

要启用修复的子集,请使用 --select 选项。例如,要修复各种类型的缩进问题

$ autopep8 --select=E1,W1 <filename>

如果正在修复的文件很大,您可能希望启用详细进度消息

$ autopep8 -v <filename>

传递 --experimental 启用以下功能

  • 根据长度缩短代码行

$ autopep8 --experimental <filename>

禁用逐行

可以通过在文件中使用 autopep8: off 禁用 autopep8,然后重新启用 autopep8: on 来在文件中禁用 autopep8 直到再次启用。

# autopep8: off
    [
        [23, 23, 13, 43],
        [32, 34, 34, 34],
        [56, 34, 34, 11],
        [10, 10, 10, 10],
    ]
# autopep8: on

fmt: offfmt: on 也是有效的。

作为模块使用

使用 autopep8 作为模块的最简单方法是使用 fix_code() 函数

>>> import autopep8
>>> autopep8.fix_code('x=       123\n')
'x = 123\n'

或者使用选项

>>> import autopep8
>>> autopep8.fix_code('print( 123 )\n',
...                   options={'ignore': ['E']})
'print( 123 )\n'

配置

默认情况下,如果 $HOME/.config/pycodestyle (在 Windows 环境中为 ~\.pycodestyle)存在,它将被用作全局配置文件。或者,您可以使用 --global-config 选项指定全局配置文件。

此外,如果目标文件所在的目录中存在 setup.cfgtox.ini.pep8.flake8 文件,它们将被用作配置文件。

pep8pycodestyleflake8 可以作为配置的一部分。

配置文件示例

[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

与pre-commit一起使用

autopep8 可以作为 pre-commit 的钩子使用。

要将 autopep8 添加为插件,请在您的配置中添加以下仓库定义

repos:
-   repo: https://github.com/hhatto/autopep8
    rev: ...  # select the tag or revision you want, or run `pre-commit autoupdate`
    hooks:
    -   id: autopep8

测试

测试用例位于 test/test_autopep8.py 中。它们可以通过 python test/test_autopep8.py 或通过 tox 直接运行。后者对于针对多个 Python 解释器进行测试很有用。(我们目前针对 CPython 版本 3.8、3.9、3.10、3.11 和 3.12 进行测试。我们还针对 PyPy 进行测试。)

通过 test/acid.py 提供广泛的测试。此脚本会对 Python 代码运行 autopep8 并检查代码修复的正确性和完整性。它可以检查字节码是否保持不变。test/acid_pypi.py 利用 acid.py 测试 PyPI 上最新发布的包。

故障排除

pkg_resources.DistributionNotFound

如果您正在使用过时的 setuptools 版本,则在尝试运行 autopep8 时可能会遇到 pkg_resources.DistributionNotFound。尝试升级 setuptools 以解决这个问题

$ pip install --upgrade setuptools

如果您要将程序安装到系统中,请使用 sudo

项目详情


发布历史 发布通知 | RSS 源

下载文件

下载适用于您平台的文件。如果您不确定选择哪一个,请了解更多关于安装包的信息。

源代码分发

autopep8-2.3.1.tar.gz (92.1 kB 查看哈希值)

上传时间 源代码

构建分发

autopep8-2.3.1-py2.py3-none-any.whl (45.7 kB 查看哈希值)

上传时间 Python 2 Python 3