# YAPF: Google's Configurable Python Code Formatter

> YAPF is a Python formatter that applies a clang-format-style reformatting algorithm to Python source files. It is configurable through named style presets and fine-grained knobs, making it a practical choice for teams that need more control over formatting than opinionated tools allow.

**google/yapf** — A formatter for Python files

- Repository: https://github.com/google/yapf
- Stars: 13,987 · Forks: 909
- Language: Python
- License: Apache-2.0
- Published: 2026-09-21 · Updated: 2026-09-21 · Language: en
- Canonical page: https://hysenlabs.com/projects/google-yapf

## What Problem YAPF Solves and Who Should Use It

YAPF addresses the time engineers spend manually formatting Python code to conform to a style guide. The formatter's goal, as stated in the README, is that "the code YAPF produces is as good as the code that a programmer would write if they were following the style guide." Instead of patching a file to fix individual style violations, YAPF recalculates the entire layout of each reformatted construct using an algorithm inspired by clang-format.

The primary audience is Python teams that have an existing style convention they want to automate. YAPF is particularly useful for codebases that follow the Google Python Style Guide or a PEP 8 derivative, since both are available as named presets. It is also practical for teams that want to block unformatted code in CI pipelines using the --diff flag, which returns a non-zero exit code when changes are needed.

YAPF is not an officially supported Google product, a fact the README states explicitly. Its pyproject.toml classifies it as Development Status 4 - Beta, which means the output format can change between releases.

## The Reformatting Algorithm Behind YAPF

Most Python formatters work by detecting and fixing style violations one at a time. YAPF takes a different approach: it parses the source code and computes what it considers the best possible formatting for the whole construct from scratch. The README describes this as taking the code and calculating "the best formatting that conforms to the configured style."

This algorithm is based on the same approach used by clang-format for C and C++. The practical consequence is that YAPF can produce formatting that a violation-fixing approach would not reach, because it reasons about the entire construct rather than each rule in isolation. A deeply nested function call that just barely fits on one line will be reformatted by weighing the full line length constraint against the configured indent width.

The trade-off is that YAPF's output is not always identical to what a human would write, and the reformatted code can look surprising when the algorithm makes a different layout decision than a developer expected. The README acknowledges this: the ultimate goal is code "as good as the code that a programmer would write," not code identical to it.

## Installing YAPF

The standard installation is through PyPI:

```bash
pip install yapf
```

Because YAPF is still in beta, the README recommends installing directly from the GitHub repository to track the latest development:

```bash
pip install git+https://github.com/google/yapf.git
```

YAPF also supports being run as a directory without a formal installation. If you have cloned the repository to a directory called DIR, you can invoke it as:

```bash
PYTHONPATH=DIR python DIR/yapf [options] ...
```

YAPF requires Python 3.7 or newer and depends on platformdirs. On Python versions below 3.11, it also requires tomli. The command accepts the -i flag to reformat files in place, -d to print a diff without modifying files, and -r to recurse through directories. Editor support is available through community plugins; the repository's EDITOR SUPPORT.md lists supported editors.

## Style Configuration: Presets and Fine-Grained Knobs

YAPF ships with four named style presets. The default is pep8, which follows PEP 8 conventions. The google preset follows the Google Python Style Guide. The yapf preset targets Google open-source projects. The facebook preset reflects Facebook's internal style.

A team can pick one of these as a base and then override individual knobs. The configuration is stored in a file with a [style] section:

```ini
[style]
based_on_style = pep8
spaces_before_comment = 4
split_before_logical_operator = true
```

YAPF searches for this configuration in the following order: the command line, a .style.yapf file in the current or any parent directory, a [yapf] section in setup.cfg, a [tool.yapf] section in pyproject.toml, and finally ~/.config/yapf/style in the home directory. The first match wins.

You can also pass style settings inline on the command line:

```bash
--style='{based_on_style: pep8, indent_width: 2}'
```

This lets you test a specific knob without modifying a configuration file. The full list of configurable knobs is in the style.py module in the repository.

To exclude files from formatting, YAPF looks for a .yapfignore file in the working directory. In pyproject.toml, the equivalent is:

```ini
[tool.yapfignore]
ignore_patterns = [
  "temp/**/*.py",
  "temp2/*.py"
]
```

The glob syntax follows UNIX filename pattern matching.

## The Python API for Programmatic Use

Beyond the command-line tool, YAPF exposes a Python API for programmatic formatting. The two primary functions are FormatCode (for formatting a string of source code) and FormatFile (for formatting a file). Both accept a style_config argument and a lines argument.

The FormatCode function takes a string and returns a tuple of the formatted string and a boolean indicating whether any changes were made:

```python
>>> from yapf.yapflib.yapf_api import FormatCode  # reformat a string of code
>>> formatted_code, changed = FormatCode("f ( a = 1, b = 2 )")
>>> formatted_code
'f(a=1, b=2)\n'
>>> changed
True
```

You can pass a style preset by name:

```python
>>> FormatCode("def g():\n  return True", style_config='pep8')[0]
'def g():\n    return True\n'
```

The programmatic API is useful for build systems, linters, or editor plugins that need to format Python code without spawning a subprocess. It is also the mechanism YAPF uses internally when running in parallel mode (-p), which formats multiple files in parallel using a process pool.

## Limitations and Cases Where YAPF Is the Wrong Tool

YAPF's beta status is a real constraint. The README states clearly that "the released version may change often." If two engineers run different YAPF versions on the same file, they may produce different output. For a team using YAPF in CI, this means all developers and CI agents must run the same pinned version. Failing to pin creates formatting-only diffs in code reviews, which obscure substantive changes.

YAPF's extensive configurability is also a limitation in disguise. A team that spends significant time tuning style knobs is deferring the harder question of agreeing on a style. The more knobs are exposed, the more likely teams are to disagree about their values.

YAPF does not sort imports. If import ordering is part of your style enforcement, you need a separate tool such as isort or ruff for that step.

Editor integration depends on community-maintained plugins rather than first-party support. Coverage and maintenance quality vary by editor.

## YAPF vs. Black: Which Python Formatter to Choose

Black is a widely used Python formatter and is often the first comparison engineers make when evaluating YAPF. The central difference is configurability. Black is intentionally opinionated: it enforces a single style with almost no user-facing knobs, and its documentation frames this as a feature. YAPF exposes dozens of knobs, all adjustable through the configuration file.

For a team starting a new project with no existing style requirements, Black's zero-configuration approach avoids the discussion about which knobs to set. For a team migrating a large codebase that already follows a specific style, YAPF's based_on_style setting and knob system give more control over what the reformatter does to existing code.

Black also has a stable output guarantee from version to version, which YAPF does not yet offer as a beta-stage project. Teams that need to compare diffs across releases without formatter noise should account for this when choosing.

## Conclusion

YAPF suits Python teams that want automated formatting but cannot accept a fully opinionated tool with no style flexibility. Its beta status means the output format can change between releases, so pinning the version in your CI and tooling lockfiles is important if reproducibility across machines matters. Teams that want minimal configuration overhead and can accept a single enforced style are better served by Black. If your codebase already follows a Google Python Style Guide-derived standard, YAPF's google preset matches that convention without manual knob-tuning. Before adopting YAPF, verify that your editor has an active community plugin and that the YAPF version in local environments matches the version in CI.

## FAQ

### How do I run YAPF on all Python files in a directory recursively?

Pass the -r flag for recursive operation and -i to format in place. Without -i, YAPF prints the reformatted code to stdout without modifying files. Use -d instead of -i to see a diff of what would change.

### Does YAPF work with pyproject.toml for configuration?

Yes. YAPF reads style settings from the [tool.yapf] section of a pyproject.toml file in the current or any parent directory. It also reads exclusion patterns from [tool.yapfignore] with an ignore_patterns key.

### Is YAPF suitable for enforcing formatting in a CI pipeline?

Yes. Run YAPF with the --diff flag, which returns a non-zero exit code when any file would be changed. This lets you block merges when files have not been formatted. Pin the YAPF version in your CI environment to ensure consistent output across machines.

## Sources

- [google/yapf on GitHub](https://github.com/google/yapf)
- [Issues](https://github.com/google/yapf/issues)
- [License: Apache-2.0](https://github.com/google/yapf/blob/main/LICENSE)
- [README](https://github.com/google/yapf/blob/main/README.md)

---

Hysen Labs editorial analysis, written from the project's own repository and release notes. Cite the canonical page: https://hysenlabs.com/projects/google-yapf
