autopep8
autopep8 is a tool that automatically formats Python code to conform to the PEP 8 style guide. It fixes most PEP 8 issues that can be automatically fixed. Currently at version 2.3.2, it maintains an active release schedule with several updates per year addressing bug fixes, new Python version support, and rule enhancements.
Warnings
- breaking Python version compatibility has changed. autopep8 v2.3.2 dropped support for Python 3.8 and now requires Python 3.9+. Previous versions like v2.1.0 dropped Python 3.7 support.
- deprecated The `--experimental` command-line option was deprecated in autopep8 v2.2.0.
- gotcha autopep8 has a direct dependency on `pycodestyle`, and specific versions of `autopep8` might require a minimum version of `pycodestyle`. For instance, autopep8 v2.3.0 requires `pycodestyle v2.12.0+`.
- gotcha autopep8 uses `pyproject.toml` (under `[tool.autopep8]`) or `setup.cfg` (under `[autopep8]`) for configuration. It does not look for a dedicated `.autopep8` or `autopep8.cfg` file.
- gotcha autopep8 fixes most, but not all, PEP 8 issues automatically. The `--aggressive` option (which can be specified multiple times for higher levels of aggressiveness) is required for certain complex fixes, but even then, some issues might require manual intervention.
Install
-
pip install autopep8
Imports
- fix_code
import autopep8 fixed_code = autopep8.fix_code(source, options={})
Quickstart
import autopep8
# Sample code with PEP8 violations
source_code = """
def my_func ( arg1 , arg2 ):
if (True): # E712 comparison to True
return arg1+arg2
"""
print("Original code:")
print(source_code)
# Fix the code with default options
# An empty dictionary for options applies default autopep8 behavior.
fixed_code = autopep8.fix_code(source_code, options={})
print("\nFixed code (default options):")
print(fixed_code)
# Fix with specific options, e.g., higher aggressiveness
# Note: Certain fixes (like E712) may require higher aggressive levels.
options_aggressive = {'aggressive': 1}
fixed_code_aggressive = autopep8.fix_code(source_code, options=options_aggressive)
print("\nFixed code (aggressive=1):")
print(fixed_code_aggressive)
# Command line usage example (run in your shell):
# echo "def my_func ( arg1 , arg2 ):\n return arg1+arg2" > example.py
# autopep8 --in-place example.py
# cat example.py # Will show the formatted code