前言

autopep8 automatically formats Python code to conform to the PEP 8 style guide. It uses the pycodestyle utility to determine what parts of the code needs to be formatted. autopep8 is capable of fixing most of the formatting issues that can be reported by pycodestyle.

操作系统:Windows 11 家庭中文版

参考文档

  1. hhatto/autopep8
  2. pypi/autopep
  3. Formatting Python in VS Code

Formatting Python in VS Code

source link: https://code.visualstudio.com/docs/python/formatting

格式化使源代码更容易被人类阅读。通过在运算符周围强制执行特定的规则和约定,如行距、缩进和行间距,代码变得更加直观和易于理解。您可以在autopep8页面上查看示例。请记住,格式化不会影响代码本身的功能。

通过分析常见的语法、风格和功能错误以及非常规的编程实践,lting有助于防止错误。虽然格式化和lting之间有一点重叠,但这两种功能是互补的。

选择格式化程序

VS Code Marketplace中搜索您选择的格式化程序扩展。

Microsoft发布了以下格式扩展:

社区提供的格式扩展:

此外,以下是支持导入排序的格式化程序扩展:

注意:如果您在上表或Marketplace中没有找到您喜欢的格式化程序,您可以通过扩展添加对它的支持。您可以使用Python扩展模板将新的Python工具集成到VS Code中。

设置默认格式化程序

Once you install a formatter extension, you can select it as the default formatter for Python files in VS Code by following the steps below:

  1. Open a Python file in VS Code.
  2. Right-click on the editor to display the context menu.
  3. Select Format Document With…
  4. Select Configure Default Formatter… from the drop-down menu.
  5. Select your preferred formatter extension from the list.

Alternatively, you can set it as the default formatter for all Python files by setting "editor.defaultFormatter" in your User settings.json file, under a [python] scope. You can open settings.json with the Preferences: Open User Settings (JSON) command.

For example, to set Black Formatter as the default formatter, add the following setting to your User settings.json file:

1
2
3
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter"
}

In order to set a formatter extension as an import sorter, you can set your preference under "editor.codeActionsOnSave" in your User settings.json file or your Workspace settings.json file, under a [python] scope. You can open these settings.json files using the Preferences: Open User Settings (JSON) and Preferences: Open Workspace Settings (JSON) commands respectively. This will enable import sorting on save for all Python files.

For example, to set Ruff as your preferred import sorter, you can add the following setting to your User settings.json or your Workspace settings.json file:

1
2
3
4
5
6
7
{
"[python]": {
"editor.codeActionsOnSave": {
"source.organizeImports.ruff": "explicit"
}
}
}

格式化您的代码

You can format your code by right-clicking on the editor and selecting Format Document, or by using the Shift+Alt+F keyboard shortcut.

You can also add the following setting to your User settings.json file to enable formatting on save for your code:

1
2
3
"[python]": {
"editor.formatOnSave": true
}

常规格式设置

您可以参考每个格式化程序扩展的README以获取有关支持设置的更多详细信息。大多数格式化程序扩展都支持以下设置:

Setting Suffix Default value Description
args [] Arguments to be passed to the formatter. Each argument should be passed as a separate string in the array. For example: black-formatter.args: ["--line-length", "100"]
importStrategy useBundled When set to useBundled, the extension uses the version of the tool that it ships with. When set to fromEnvironment, it attempts to load from your selected Python environment first, otherwise it falls back to the bundled version.
path "" Path to the formatter binary to be used for formatting. Note: Using this option may slow down formatting.
interpreter [] When set to a path to a Python executable, the extension will use that to launch the formatter server and its subprocesses.
showNotifications off Controls when notifications are displayed by the extension. Supported values are off, always, onError, and onWarning.

Installation

From pip

1
$ pip install --upgrade autopep8

Consider using the --user option.

Requirements

autopep8 requires pycodestyle.

Usage

To modify a file in place (with aggressive level 2):

1
$ autopep8 --in-place --aggressive --aggressive <filename>

Before running autopep8.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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)

After running autopep8.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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)

Options:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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.

Features

autopep8 fixes the following issues reported by pycodestyle:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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 also fixes some issues not found by pycodestyle.

  • Normalize files with mixed line endings.
  • Put a blank line between a class docstring and its first method
    declaration. (Enabled with E301.)
  • Remove blank lines between a function declaration and its docstring. (Enabled
    with E303.)

autopep8 avoids fixing some issues found by pycodestyle.

  • E112/E113 for non comments are reports of bad indentation that break
    syntax rules. These should not be modified at all.
  • E265, which refers to spacing after comment hash, is ignored if the
    comment looks like code. autopep8 avoids modifying these since they are not
    real comments. If you really want to get rid of the pycodestyle warning,
    consider just removing the commented-out code. (This can be automated via
    eradicate.)

More advanced usage

By default autopep8 only makes whitespace changes. Thus, by default, it does
not fix E711 and E712. (Changing x == None to x is None may
change the meaning of the program if x has its __eq__ method
overridden.) Nor does it correct deprecated code W6. To enable these
more aggressive fixes, use the --aggressive option:

1
$ autopep8 --aggressive <filename>

Use multiple --aggressive to increase the aggressiveness level. For
example, E712 requires aggressiveness level 2 (since x == True could be
changed to either x or x is True, but autopep8 chooses the former).

--aggressive will also shorten lines more aggressively. It will also remove
trailing whitespace more aggressively. (Usually, we don’t touch trailing
whitespace in docstrings and other multiline strings. And to do even more
aggressive changes to docstrings, use docformatter.)

To enable only a subset of the fixes, use the --select option. For example,
to fix various types of indentation issues:

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

If the file being fixed is large, you may want to enable verbose progress
messages:

1
$ autopep8 -v <filename>

Passing in --experimental enables the following functionality:

  • Shortens code lines by taking its length into account
1
$ autopep8 --experimental <filename>

Disabling line-by-line

It is possible to disable autopep8 untill it it turned back on again in the file, using autopep8: off and then renabling autopep8: on.

1
2
3
4
5
6
7
8
# autopep8: off
[
[23, 23, 13, 43],
[32, 34, 34, 34],
[56, 34, 34, 11],
[10, 10, 10, 10],
]
# autopep8: on

fmt: off and fmt: on are also valid.

Use as a module

The simplest way of using autopep8 as a module is via the fix_code() function:

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

Or with options:

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

Configuration

By default, if $HOME/.config/pycodestyle (~\.pycodestyle in Windows
environment) exists, it will be used as global configuration file.
Alternatively, you can specify the global configuration file with the
--global-config option.

Also, if setup.cfg, tox.ini, .pep8 and .flake8 files exist
in the directory where the target file exists, it will be used as the
configuration file.

pep8, pycodestyle, and flake8 can be used as a section.

configuration file example:

1
2
3
[pycodestyle]
max_line_length = 120
ignore = E501

pyproject.toml

autopep8 can also use pyproject.toml.
The section must be [tool.autopep8], and pyproject.toml takes precedence
over any other configuration files.

configuration file example:

1
2
3
4
5
6
[tool.autopep8]
max_line_length = 120
ignore = "E501,W6" # or ["E501", "W6"]
in-place = true
recursive = true
aggressive = 3

Usage with pre-commit

autopep8 can be used as a hook for pre-commit.

To add autopep8 as a plugin, add this repo definition to your configuration:

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

Testing

Test cases are in test/test_autopep8.py. They can be run directly via
python test/test_autopep8.py or via tox. The latter is useful for
testing against multiple Python interpreters. (We currently test against
CPython versions 3.8, 3.9, 3.10, 3.11 and 3.12. We also test against PyPy.)

Broad spectrum testing is available via test/acid.py. This script runs
autopep8 against Python code and checks for correctness and completeness of the
code fixes. It can check that the bytecode remains identical.
test/acid_pypi.py makes use of acid.py to test against the latest
released packages on PyPI.

Troubleshooting

pkg_resources.DistributionNotFound

If you are using an ancient version of setuptools, you might encounter
pkg_resources.DistributionNotFound when trying to run autopep8. Try
upgrading setuptools to workaround this setuptools problem:

1
$ pip install --upgrade setuptools

Use sudo if you are installing to the system.

结语

第一百六十七篇博文写完,开心!!!!

今天,也是充满希望的一天。