Introduction
YAPF takes a different approach from other Python formatters. Rather than only fixing style violations, it reformats the entire file to produce the best formatting conforming to the configured style, similar to how clang-format works for C++. This eliminates debates about formatting during code review.
What YAPF Does
- Reformats Python code to match a specified style (PEP 8, Google, Chromium, Facebook)
- Uses a penalty-based algorithm to find optimal line-breaking decisions
- Handles complex expressions, nested containers, and function call chains
- Integrates with editors, pre-commit hooks, and CI pipelines
- Supports partial formatting of selected code regions
Architecture Overview
YAPF parses Python source into a concrete syntax tree, then applies a reformatting algorithm inspired by clang-format. It assigns penalties to line breaks and excess whitespace, then uses dynamic programming to find the lowest-cost layout. The result is deterministic output regardless of the original formatting.
Self-Hosting & Configuration
- Install from PyPI: pip install yapf
- Configure via .style.yapf, setup.cfg, or pyproject.toml
- Set BASED_ON_STYLE to google, pep8, chromium, or facebook as a starting point
- Override individual knobs like COLUMN_LIMIT, INDENT_WIDTH, SPLIT_BEFORE_LOGICAL_OPERATOR
- Use # yapf: disable / # yapf: enable comments to skip specific blocks
Key Features
- Deterministic output: same input always produces same output regardless of original layout
- Penalty-based algorithm finds globally optimal formatting rather than greedy local fixes
- Four built-in base styles covering major Python community conventions
- Supports Python 3.6+ syntax including f-strings and walrus operator
- Pre-commit hook integration for automatic formatting on git commit
Comparison with Similar Tools
- Black — zero-configuration philosophy with fewer knobs; YAPF offers more style customization
- autopep8 — only fixes PEP 8 violations; YAPF reformats entire structure for optimal layout
- Ruff formatter — extremely fast Rust-based formatter; YAPF is pure Python but more configurable
- isort — only handles import sorting; YAPF formats all code but can be paired with isort
FAQ
Q: How does YAPF differ from Black? A: Black enforces one style with minimal configuration. YAPF offers many configurable knobs and multiple base styles, letting teams tailor formatting to their preferences.
Q: Can I format only changed lines? A: Yes. Use --lines or --diff-based formatting to only reformat modified regions, useful for large legacy codebases.
Q: Does YAPF support type annotations? A: Yes. YAPF handles PEP 484/526 type annotations, PEP 604 union syntax, and complex generic types.
Q: Is YAPF actively maintained? A: Yes. YAPF is maintained by Google engineers and continues to receive updates for new Python syntax.