4 Summary: A tool that automatically formats Python code to conform to the PEP 8 style guide
5 Home-page: https://github.com/hhatto/autopep8
7 Author-email: hhatto.jp@gmail.com
9 Keywords: automation,pep8,format,pycodestyle
10 Classifier: Development Status :: 5 - Production/Stable
11 Classifier: Environment :: Console
12 Classifier: Intended Audience :: Developers
13 Classifier: License :: OSI Approved :: MIT License
14 Classifier: Operating System :: OS Independent
15 Classifier: Programming Language :: Python
16 Classifier: Programming Language :: Python :: 3
17 Classifier: Programming Language :: Python :: 3.6
18 Classifier: Programming Language :: Python :: 3.7
19 Classifier: Programming Language :: Python :: 3.8
20 Classifier: Programming Language :: Python :: 3.9
21 Classifier: Programming Language :: Python :: 3.10
22 Classifier: Topic :: Software Development :: Libraries :: Python Modules
23 Classifier: Topic :: Software Development :: Quality Assurance
24 Requires-Python: >=3.6
26 License-File: AUTHORS.rst
27 Requires-Dist: pycodestyle >=2.10.0
28 Requires-Dist: tomli ; python_version < "3.11"
34 .. image:: https://img.shields.io/pypi/v/autopep8.svg
35 :target: https://pypi.org/project/autopep8/
38 .. image:: https://github.com/hhatto/autopep8/workflows/Python%20package/badge.svg
39 :target: https://github.com/hhatto/autopep8/actions
42 .. image:: https://codecov.io/gh/hhatto/autopep8/branch/main/graph/badge.svg
43 :target: https://codecov.io/gh/hhatto/autopep8
46 autopep8 automatically formats Python code to conform to the `PEP 8`_ style
47 guide. It uses the pycodestyle_ utility to determine what parts of the code
48 needs to be formatted. autopep8 is capable of fixing most of the formatting
49 issues_ that can be reported by pycodestyle.
51 .. _PEP 8: https://www.python.org/dev/peps/pep-0008/
52 .. _issues: https://pycodestyle.readthedocs.org/en/latest/intro.html#error-codes
62 $ pip install --upgrade autopep8
64 Consider using the ``--user`` option_.
66 .. _option: https://pip.pypa.io/en/latest/user_guide/#user-installs
72 autopep8 requires pycodestyle_.
74 .. _pycodestyle: https://github.com/PyCQA/pycodestyle
80 To modify a file in place (with aggressive level 2)::
82 $ autopep8 --in-place --aggressive --aggressive <filename>
84 Before running autopep8.
86 .. code-block:: python
91 ####This is a long comment. This should be wrapped to fit within 72 characters.
92 some_tuple=( 1,2, 3,'a' );
93 some_variable={'long':'Long code lines should be wrapped within 79 characters.',
94 'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
95 'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
96 20,300,40000,500000000,60000000000000000]}}
97 return (some_tuple, some_variable)
98 def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key(''));
99 class Example3( object ):
100 def __init__ ( self, bar ):
101 #Comments should have a space after the hash.
102 if bar : bar+=1; bar=bar* bar ; return bar
105 Indentation in multiline strings should not be touched.
106 Only actual code should be reindented.
108 return (sys.path, some_string)
110 After running autopep8.
112 .. code-block:: python
119 # This is a long comment. This should be wrapped to fit within 72
121 some_tuple = (1, 2, 3, 'a')
123 'long': 'Long code lines should be wrapped within 79 characters.',
130 'This is a long string that goes on'],
132 'inner': 'This whole logical line should be wrapped.',
140 return (some_tuple, some_variable)
143 def example2(): return ('' in {'f': 2}) in {'has_key() is deprecated': True}
146 class Example3(object):
147 def __init__(self, bar):
148 # Comments should have a space after the hash.
155 Indentation in multiline strings should not be touched.
156 Only actual code should be reindented.
158 return (sys.path, some_string)
162 usage: autopep8 [-h] [--version] [-v] [-d] [-i] [--global-config filename]
163 [--ignore-local-config] [-r] [-j n] [-p n] [-a]
164 [--experimental] [--exclude globs] [--list-fixes]
165 [--ignore errors] [--select errors] [--max-line-length n]
166 [--line-range line line] [--hang-closing] [--exit-code]
169 Automatically formats Python code to conform to the PEP 8 style guide.
171 positional arguments:
172 files files to format or '-' for standard in
175 -h, --help show this help message and exit
176 --version show program's version number and exit
177 -v, --verbose print verbose messages; multiple -v result in more
179 -d, --diff print the diff for the fixed source
180 -i, --in-place make changes to files in place
181 --global-config filename
182 path to a global pep8 config file; if this file does
183 not exist then this is ignored (default:
185 --ignore-local-config
186 don't look for and apply local config files; if not
187 passed, defaults are updated with any config files in
188 the project's root directory
189 -r, --recursive run recursively over directories; must be used with
191 -j n, --jobs n number of parallel jobs; match CPU count if value is
193 -p n, --pep8-passes n
194 maximum number of additional pep8 passes (default:
196 -a, --aggressive enable non-whitespace changes; multiple -a result in
197 more aggressive changes
198 --experimental enable experimental fixes
199 --exclude globs exclude file/directory names that match these comma-
201 --list-fixes list codes for fixes; used by --ignore and --select
202 --ignore errors do not fix these errors/warnings (default:
204 --select errors fix only these errors/warnings (e.g. E4,W)
205 --max-line-length n set maximum allowed line length (default: 79)
206 --line-range line line, --range line line
207 only fix errors found within this inclusive range of
208 line numbers (e.g. 1 99); line numbers are indexed at
210 --hang-closing hang-closing option passed to pycodestyle
211 --exit-code change to behavior of exit code. default behavior of
212 return value, 0 is no differences, 1 is error exit.
213 return 2 when add this option. 2 is exists
220 autopep8 fixes the following issues_ reported by pycodestyle_::
222 E101 - Reindent all lines.
223 E11 - Fix indentation.
224 E121 - Fix indentation to be a multiple of four.
225 E122 - Add absent indentation for hanging indentation.
226 E123 - Align closing bracket to match opening bracket.
227 E124 - Align closing bracket to match visual indentation.
228 E125 - Indent to distinguish line from next logical line.
229 E126 - Fix over-indented hanging indentation.
230 E127 - Fix visual indentation.
231 E128 - Fix visual indentation.
232 E129 - Fix visual indentation.
233 E131 - Fix hanging indent for unaligned continuation line.
234 E133 - Fix missing indentation for closing bracket.
235 E20 - Remove extraneous whitespace.
236 E211 - Remove extraneous whitespace.
237 E22 - Fix extraneous whitespace around keywords.
238 E224 - Remove extraneous whitespace around operator.
239 E225 - Fix missing whitespace around operator.
240 E226 - Fix missing whitespace around arithmetic operator.
241 E227 - Fix missing whitespace around bitwise/shift operator.
242 E228 - Fix missing whitespace around modulo operator.
243 E231 - Add missing whitespace.
244 E241 - Fix extraneous whitespace around keywords.
245 E242 - Remove extraneous whitespace around operator.
246 E251 - Remove whitespace around parameter '=' sign.
247 E252 - Missing whitespace around parameter equals.
248 E26 - Fix spacing after comment hash for inline comments.
249 E265 - Fix spacing after comment hash for block comments.
250 E266 - Fix too many leading '#' for block comments.
251 E27 - Fix extraneous whitespace around keywords.
252 E301 - Add missing blank line.
253 E302 - Add missing 2 blank lines.
254 E303 - Remove extra blank lines.
255 E304 - Remove blank line following function decorator.
256 E305 - Expected 2 blank lines after end of function or class.
257 E306 - Expected 1 blank line before a nested definition.
258 E401 - Put imports on separate lines.
259 E402 - Fix module level import not at top of file
260 E501 - Try to make lines fit within --max-line-length characters.
261 E502 - Remove extraneous escape of newline.
262 E701 - Put colon-separated compound statement on separate lines.
263 E70 - Put semicolon-separated compound statement on separate lines.
264 E711 - Fix comparison with None.
265 E712 - Fix comparison with boolean.
266 E713 - Use 'not in' for test for membership.
267 E714 - Use 'is not' test for object identity.
268 E721 - Use "isinstance()" instead of comparing types directly.
269 E722 - Fix bare except.
270 E731 - Use a def when use do not assign a lambda expression.
271 W291 - Remove trailing whitespace.
272 W292 - Add a single newline at the end of the file.
273 W293 - Remove trailing whitespace on blank line.
274 W391 - Remove trailing blank lines.
275 W503 - Fix line break before binary operator.
276 W504 - Fix line break after binary operator.
277 W605 - Fix invalid escape sequence 'x'.
278 W690 - Fix various deprecated code (via lib2to3).
280 autopep8 also fixes some issues not found by pycodestyle_.
282 - Correct deprecated or non-idiomatic Python code (via ``lib2to3``). Use this
283 for making Python 2.7 code more compatible with Python 3. (This is triggered
284 if ``W690`` is enabled.)
285 - Normalize files with mixed line endings.
286 - Put a blank line between a class docstring and its first method
287 declaration. (Enabled with ``E301``.)
288 - Remove blank lines between a function declaration and its docstring. (Enabled
291 autopep8 avoids fixing some issues found by pycodestyle_.
293 - ``E112``/``E113`` for non comments are reports of bad indentation that break
294 syntax rules. These should not be modified at all.
295 - ``E265``, which refers to spacing after comment hash, is ignored if the
296 comment looks like code. autopep8 avoids modifying these since they are not
297 real comments. If you really want to get rid of the pycodestyle_ warning,
298 consider just removing the commented-out code. (This can be automated via
301 .. _eradicate: https://github.com/myint/eradicate
307 By default autopep8 only makes whitespace changes. Thus, by default, it does
308 not fix ``E711`` and ``E712``. (Changing ``x == None`` to ``x is None`` may
309 change the meaning of the program if ``x`` has its ``__eq__`` method
310 overridden.) Nor does it correct deprecated code ``W6``. To enable these
311 more aggressive fixes, use the ``--aggressive`` option::
313 $ autopep8 --aggressive <filename>
315 Use multiple ``--aggressive`` to increase the aggressiveness level. For
316 example, ``E712`` requires aggressiveness level 2 (since ``x == True`` could be
317 changed to either ``x`` or ``x is True``, but autopep8 chooses the former).
319 ``--aggressive`` will also shorten lines more aggressively. It will also remove
320 trailing whitespace more aggressively. (Usually, we don't touch trailing
321 whitespace in docstrings and other multiline strings. And to do even more
322 aggressive changes to docstrings, use docformatter_.)
324 .. _docformatter: https://github.com/myint/docformatter
326 To enable only a subset of the fixes, use the ``--select`` option. For example,
327 to fix various types of indentation issues::
329 $ autopep8 --select=E1,W1 <filename>
331 If the file being fixed is large, you may want to enable verbose progress
334 $ autopep8 -v <filename>
336 Passing in ``--experimental`` enables the following functionality:
338 - Shortens code lines by taking its length into account
342 $ autopep8 --experimental <filename>
344 Disabling line-by-line
345 ----------------------
347 It is possible to disable autopep8 untill it it turned back on again in the file, using ``autopep8: off`` and then renabling ``autopep8: on``.
349 .. code-block:: python
360 ``fmt: off`` and ``fmt: on`` are also valid.
365 The simplest way of using autopep8 as a module is via the ``fix_code()``
369 >>> autopep8.fix_code('x= 123\n')
375 >>> autopep8.fix_code('print( 123 )\n',
376 ... options={'ignore': ['E']})
383 By default, if ``$HOME/.config/pycodestyle`` (``~\.pycodestyle`` in Windows
384 environment) exists, it will be used as global configuration file.
385 Alternatively, you can specify the global configuration file with the
386 ``--global-config`` option.
388 Also, if ``setup.cfg``, ``tox.ini``, ``.pep8`` and ``.flake8`` files exist
389 in the directory where the target file exists, it will be used as the
392 ``pep8``, ``pycodestyle``, and ``flake8`` can be used as a section.
394 configuration file example::
397 max_line_length = 120
403 autopep8 can also use ``pyproject.toml``.
404 The section must be ``[tool.autopep8]``, and ``pyproject.toml`` takes precedence
405 over any other configuration files.
407 configuration file example::
410 max_line_length = 120
411 ignore = "E501,W6" # or ["E501", "W6"]
416 Usage with pre-commit
417 =====================
419 autopep8 can be used as a hook for pre-commit_.
421 To add autopep8 as a plugin, add this repo definition to your configuration:
426 - repo: https://github.com/hhatto/autopep8
427 rev: ... # select the tag or revision you want, or run `pre-commit autoupdate`
431 .. _`pre-commit`: https://pre-commit.com
437 Test cases are in ``test/test_autopep8.py``. They can be run directly via
438 ``python test/test_autopep8.py`` or via tox_. The latter is useful for
439 testing against multiple Python interpreters. (We currently test against
440 CPython versions 3.7, 3.8, 3.9 and 3.10. We also test against PyPy.)
442 .. _`tox`: https://pypi.org/project/tox/
444 Broad spectrum testing is available via ``test/acid.py``. This script runs
445 autopep8 against Python code and checks for correctness and completeness of the
446 code fixes. It can check that the bytecode remains identical.
447 ``test/acid_pypi.py`` makes use of ``acid.py`` to test against the latest
448 released packages on PyPI.
454 ``pkg_resources.DistributionNotFound``
455 --------------------------------------
457 If you are using an ancient version of ``setuptools``, you might encounter
458 ``pkg_resources.DistributionNotFound`` when trying to run ``autopep8``. Try
459 upgrading ``setuptools`` to workaround this ``setuptools`` problem::
461 $ pip install --upgrade setuptools
463 Use ``sudo`` if you are installing to the system.
474 .. _PyPI: https://pypi.org/project/autopep8/
475 .. _GitHub: https://github.com/hhatto/autopep8
476 .. _`Travis CI`: https://travis-ci.org/hhatto/autopep8
477 .. _`Coveralls`: https://coveralls.io/r/hhatto/autopep8