$ show hhatto/autopep8
autopep8 is a production-grade Python code formatter that automatically modifies source code to conform to the PEP 8 style guide. It operates as both a CLI tool and a library, using pycodestyle to detect violations and applying targeted fixes for most reported error codes (E1xx, E2xx, E3xx, E4xx, E5xx, E7xx, E9xx, and W6xx). The tool supports incremental formatting, aggressive mode, configuration file inheritance (pyproject.toml, setup.cfg, tox.ini, .pep8, .flake8), and integration with pre-commit hooks and editors like Vim. The entire logic is contained in a single monolithic module (autopep8.py), which includes a complex line-wrapping system for long lines, a reindentation engine, and token-based heuristics. The test suite is exceptionally thorough, with fixture-based regression tests and an 'acid test' framework that validates correctness on arbitrary Python files (including live PyPI packages). While the single-file architecture limits modularity, the internal components are well-factored and demonstrate strong engineering practice.
The LLM identified 4 files worth highlighting for reuse:
The Reindenter class is a self-contained engine for correcting indentation (E111, E112, E113, E114). It is adapted from Tim Peters' original reindent.py and can be extracted as a standalone library for any Python codebase needing indentation repair. It operates on a line-by-line basis, tracking statement depth and fixme markers, and does not depend on other autopep8 internals.
CachedTokenizer wraps Python's tokenize module to avoid re-tokenizing the same source text multiple times during a single formatting run. It is a simple, reusable performance optimization pattern applicable to any tool that repeatedly parses Python code. Implementation is minimal and dependency-free (only standard library).
The acid test script is a reusable validation harness for code formatters. It runs autopep8 on any Python file, checks syntax preservation, optionally compares bytecode equivalence, and verifies that pycodestyle no longer reports errors after formatting. This pattern can be adapted to test other transformation tools (e.g., black, isort) by replacing the command and expected output criteria.
The line-wrapping subsystem handles E501 (line too long) by reconstructing logical lines from tokens, generating multiple candidate shortenings (e.g., breaking before operators, after commas, using parentheses), and ranking them by a heuristic score. The Container and Atom classes model nested expressions and operator precedence. This is a non-trivial, self-contained algorithm that could be extracted as a general-purpose Python line-shortening library.