# Python code formatter libraries

Python code formatters rewrite source files in one consistent style. These libraries format code on save or in a pre-commit hook so that review diffs show changes in behavior rather than style.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Ruff](#ruff) | 428.0M | 51.3K | Nov 2026 | MIT |
| [Black](#black) | 116.2M | 42.2K | Oct 2026 | MIT |
| [isort](#isort) | 98.7M | 7.0K | Sep 2026 | MIT |
| [autopep8](#autopep) | 8.2M | 4.7K | Jan 2025 | MIT License |
| [YAPF](#yapf) | 5.7M | 14.0K | Nov 2024 | Apache Software License |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Ruff](#ruff) has the most installs and the most GitHub stars.

## Capabilities

| Library | Python formatting API | Line-range formatting |
| --- | --- | --- |
| [Ruff](#ruff) | No | Yes |
| [Black](#black) | Yes | Yes |
| [isort](#isort) | Yes | Undocumented |
| [autopep8](#autopep) | Yes | Yes |
| [YAPF](#yapf) | Yes | Yes |

## Libraries

### Ruff

[GitHub](https://github.com/astral-sh/ruff) · [PyPI](https://pypi.org/project/ruff) · [Docs](https://docs.astral.sh/ruff/formatter/)

Ruff's formatter is a Python code formatter that runs as `ruff format`, a subcommand of the Ruff linter. The formatter is a drop-in replacement for [Black](#black). On large Black-formatted projects such as Django and Zulip, nearly every line comes out identical. Unlike Black, Ruff lets a project set the quote style, the indent style, and line endings. With `docstring-code-format` turned on, the formatter also reformats code examples inside docstrings. The `--check` flag lists unformatted files and exits with an error status, leaving the files unchanged.

- Downloads / mo: 428.0M
- Stars: 51.3K
- Last release: 0.17.5
- License: MIT
- Capabilities: [From the Ruff docs](https://docs.astral.sh/ruff/formatter/)

**Strengths**

- **Formats docstring examples.** Turn on docstring code formatting to format the Python examples inside docstrings.
- **Formats notebooks natively.** Run ruff format on Jupyter notebooks without a separate wrapper.

**Watch out for**

- **No import sorting.** The formatter leaves import order alone. Sorting imports takes the linter's import rules first, with `ruff check --select I --fix`.
- **Not interchangeable with Black.** Ruff differs from Black in a few deliberate ways. A project uses one of the two formatters for all its files.

```sh
pip install ruff
```

**matkuki/ExCo** (163 stars)

[matkuki/ExCo](https://github.com/matkuki/ExCo) 

```python
def format_ruff_python(code: str) -> str:
    with tempfile.TemporaryDirectory() as tmpdir:  # type: ignore
        file_path: pathlib.Path = pathlib.Path(tmpdir) / "temp_ruff_formatting_file.py"
        file_path.write_text(code, encoding="utf-8")

        result: subprocess.CompletedProcess[str] = subprocess.run(
            ["ruff", "format", str(file_path)],
            capture_output=True,
            text=True,
            encoding="utf-8",  # Ensure subprocess handles UTF-8 output
        )

        if result.returncode != 0:
            raise RuntimeError(f"Ruff error:\n{result.stderr}")

        return file_path.read_text(encoding="utf-8")

```

[codequality.py](https://github.com/matkuki/ExCo/blob/a201970286d6ddaa1de922f394290d8f456c4505/codequality.py#L144-L159) · [More projects using Ruff →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20ruff%20for%20source%20formatting%2C%20generated%20modules%20and%20editor%20integrations&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
ruff format                   # Format all files in the current directory.

```

From [formatter.md](https://docs.astral.sh/ruff/formatter/)

### Black

[GitHub](https://github.com/psf/black) · [PyPI](https://pypi.org/project/black) · [Docs](https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html)

Black is a Python code formatter with almost no style settings. A project that adopts Black gives up control over formatting details. In return, every Black-formatted codebase looks alike. The `black` command takes files or directories and rewrites the code in place, keeping diffs as small as possible. Jupyter notebook support comes from installing the `jupyter` extra, as in `pip install "black[jupyter]"`. [Ruff](#ruff) follows Black's style closely as a drop-in replacement.

- Downloads / mo: 116.2M
- Stars: 42.2K
- Last release: 26.10.1
- License: MIT
- Capabilities: [From the Black docs](https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html)

**Strengths**

- **Checks the code still matches.** After formatting, Black confirms the AST is unchanged. The --fast flag skips this check.
- **Formats Jupyter notebooks.** Pass --ipynb to format any input as a notebook, such as code piped on standard input.

**Watch out for**

- **Few settings.** Choices such as quote style and indent style are fixed. [Ruff](#ruff) lets a project configure both.

```sh
pip install black
```

**SDXorg/pysd** (467 stars)

[SDXorg/pysd](https://github.com/SDXorg/pysd) 

```python
def _build_separate_module(self, elements: list, module_name: str,
                           module_dir: str) -> None:
    """
    Constructs and writes the Python representation of a specific model
    module, when the split_views=True in the read_vensim function.

    Parameters
    ----------
    elements: list
        Elements belonging to the module module_name.

    module_name: str
        Name of the module

    module_dir: str
        Path of the directory where module files will be stored.

    Returns
    -------
    None

    """
    text = textwrap.dedent('''
    """
    Module %(module_name)s
    Translated using PySD version %(version)s
    """
    ''' % {
        "module_name": ".".join(module_name.parts[1:]),
        "version": __version__,
    })
    funcs = self._generate_functions(elements)
    text += funcs
    text = black.format_file_contents(
        text, fast=True, mode=black.FileMode())

    outfile_name = module_dir / module_name.with_suffix(".py")

    with outfile_name.open("w", encoding="UTF-8") as out:
        out.write(text)

```

[pysd/builders/python/python_model_builder.py](https://github.com/SDXorg/pysd/blob/8991d119e139029d4dec712d257cf5fcc3549b8f/pysd/builders/python/python_model_builder.py#L242-L281) · [More projects using Black →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20black%20for%20source%20formatting%2C%20generated%20modules%20and%20editor%20integrations&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
black {source_file_or_directory}

```

From [README.md](https://github.com/psf/black/blob/main/README.md)

### isort

[GitHub](https://github.com/PyCQA/isort) · [PyPI](https://pypi.org/project/isort) · [Docs](https://raw.githubusercontent.com/PyCQA/isort/main/README.md)

isort sorts Python imports alphabetically and separates them into sections for the standard library, third-party packages, and project modules. The `isort` command rewrites files in place. With `--diff`, the command prints the proposed changes instead of applying them. From Python, `isort.code` returns a copy of a source string with the imports sorted. A `black` profile makes isort wrap long imports the way [Black](#black) does. With that profile set, the two tools agree on import layout.

- Downloads / mo: 98.7M
- Stars: 7.0K
- Last release: 9.0.2
- License: MIT
- Capabilities: [From the isort docs](https://raw.githubusercontent.com/PyCQA/isort/main/README.md)

**Strengths**

- **Sorts imports in a string.** Call isort.code with source text to get it back with imports sorted.
- **Works alongside Black.** Set the isort profile to black, and the two tools agree on import layout.

**Watch out for**

- **Imports only.** [Black](#black) or [Ruff](#ruff) formats the rest of each file.
- **Atomic mode off.** The `--atomic` flag skips changes that would introduce syntax errors. The flag is off by default because it stops isort from running on code written for a different Python version.

```sh
pip install isort
```

**matkuki/ExCo** (163 stars)

[matkuki/ExCo](https://github.com/matkuki/ExCo) 

```python
def format_python_code(code: str, library: str) -> str:
    # Choose formatter based on the specified library
    if library == "black":
        # Format code using Black with default settings
        formatted_code: str = black.format_str(code, mode=black.FileMode())

    elif library == "autopep8":
        # Format code using autopep8
        formatted_code = autopep8.fix_code(code)

    elif library == "yapf":
        # Format code using yapf; returns (formatted_code, changed_flag)
        formatted_code, _ = yapf.yapf_api.FormatCode(code)

    elif library == "ruff":
        # Format code using a custom wrapper for Ruff (assumes string input/output)
        formatted_code = format_ruff_python(code)

    else:
        # Raise a ValueError for unrecognized formatter names
        raise ValueError(
            f"[PYTHON-CODE-FORMATTING] Unknown formatting library selected: {library}"
        )

    # Sort and format imports using isort with Black compatibility
    formatted_code = isort.code(formatted_code, config=isort.Config(profile="black"))

    return formatted_code

```

[codequality.py](https://github.com/matkuki/ExCo/blob/a201970286d6ddaa1de922f394290d8f456c4505/codequality.py#L225-L252) · [More projects using isort →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20isort%20for%20source%20formatting%2C%20generated%20modules%20and%20editor%20integrations&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import isort

sorted_code = isort.code("import b\nimport a\n")

```

From [README.md](https://raw.githubusercontent.com/PyCQA/isort/main/README.md)

### autopep8

[GitHub](https://github.com/hhatto/autopep8) · [PyPI](https://pypi.org/project/autopep8) · [Docs](https://raw.githubusercontent.com/hhatto/autopep8/main/README.rst)

autopep8 rewrites Python code to fix the style problems that pycodestyle, a Python style checker, reports when code breaks the official Python style guide. By default, the fixes change only whitespace. Each `--aggressive` flag allows further fixes, such as replacing `x == None` with `x is None`. From Python, the `fix_code` function takes a string of source and returns the fixed string. Unlike [Black](#black), which reformats every line in its own style, autopep8 changes only the lines pycodestyle flags.

- Downloads / mo: 8.2M
- Stars: 4.7K
- Last release: 2.3.2
- License: MIT License
- Capabilities: [From the autopep8 docs](https://raw.githubusercontent.com/hhatto/autopep8/main/README.rst)

**Strengths**

- **Fixes selected rules.** Pass --select or --ignore with pycodestyle codes to choose which fixes run.
- **Formats code strings.** Call autopep8.fix_code() on a string of source code.

**Watch out for**

- **Behavior-changing fixes.** Changing `x == None` to `x is None` changes behavior when a class overrides `__eq__`. Fixes of that kind run only with `--aggressive`.
- **Some reports stay unfixed.** Bad indentation that breaks syntax, and comments that look like code, are left for a person to fix.

```sh
pip install --upgrade autopep8
```

**coala/coala-bears** (297 stars)

[coala/coala-bears](https://github.com/coala/coala-bears) 

```python
def autopep8_fix_code_cell(source, options=None, apply_config=None):
    """
    Applies autopep8.fix_code and takes care of newline characters.

    autopep8.fix_code automatically adds a final newline at the end,
    e.g. ``autopep8.fix_code('a=1')`` yields 'a = 1\\n'.
    Note that this is not related to the 'W292' flag, i.e.
    ``autopep8.fix_code('a=1', options=dict(ignore=('W292',)))`` gives
    the same result.
    For notebook code cells, this behaviour does not make sense, hence
    newline is removed if ``source`` does not end with one.
    """
    source_corrected = autopep8.fix_code(source,
                                         apply_config=apply_config,
                                         options=options)

    if not source.endswith('\n'):
        return source_corrected[:-1]

    return source_corrected

```

[bears/python/PEP8NotebookBear.py](https://github.com/coala/coala-bears/blob/7d21a59891b6ad048bbe28de097cbb5693c648c7/bears/python/PEP8NotebookBear.py#L44-L63) · [More projects using autopep8 →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20autopep8%20for%20source%20formatting%2C%20generated%20modules%20and%20editor%20integrations&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import autopep8
autopep8.fix_code('x= 123\n')

```

From [README.rst](https://raw.githubusercontent.com/hhatto/autopep8/main/README.rst)

### YAPF

[GitHub](https://github.com/google/yapf) · [PyPI](https://pypi.org/project/yapf) · [Docs](https://github.com/google/yapf/blob/main/README.md)

YAPF is a Python formatter derived from clang-format. For each piece of code, the algorithm computes the layout that best fits the configured style. That style starts from a predefined one, such as Google's, with individual settings in a `.style.yapf` file or `pyproject.toml`. Two calls make up the library API. `FormatCode` formats a string of code, while `FormatFile` reads and formats a file. Both accept a `lines` argument that limits formatting to chosen line ranges, the way editors format a selection. YAPF exposes dozens of style settings, compared with the handful in [Black](#black).

- Downloads / mo: 5.7M
- Stars: 14.0K
- Last release: 0.43.0
- License: Apache Software License
- Capabilities: [From the YAPF docs](https://github.com/google/yapf/blob/main/README.md)

**Strengths**

- **Many style settings.** Tune individual formatting knobs; the style.py module lists every one.
- **Formats chosen lines.** Pass a lines argument to format a snippet instead of the whole file, as editors do.

**Watch out for**

- **Newer syntax missing.** Type parameter syntax and the formalized f-string grammar from recent Python releases aren't supported yet.
- **Large data literals.** Large data literals can come out badly formatted. The README suggests wrapping them in `# yapf: disable` and `# yapf: enable` comments.
- **Beta releases.** The README describes YAPF as beta. Released versions may change often.

```sh
pip install yapf
```

**python-lsp/python-lsp-server** (2.6K stars)

[python-lsp/python-lsp-server](https://github.com/python-lsp/python-lsp-server) 

```python
def get_style_config(document_path, options=None):
    # Exclude file if it follows the patterns for that
    exclude_patterns_from_ignore_file = file_resources.GetExcludePatternsForDir(
        os.getcwd()
    )
    if file_resources.IsIgnored(document_path, exclude_patterns_from_ignore_file):
        return []

    # Get the default styles as a string
    # for a preset configuration, i.e. "pep8"
    style_config = file_resources.GetDefaultStyleForDir(os.path.dirname(document_path))
    if options is None:
        return style_config

    # We have options passed from LSP format request
    # let's pass them to the formatter.
    # First we want to get a dictionary of the preset style
    # to pass instead of a string so that we can modify it
    style_config = style.CreateStyleFromConfig(style_config)

    use_tabs = style_config["USE_TABS"]
    indent_width = style_config["INDENT_WIDTH"]

    if options.get("tabSize") is not None:
        indent_width = max(int(options.get("tabSize")), 1)

    if options.get("insertSpaces") is not None:
        # TODO is it guaranteed to be a boolean, or can it be a string?
        use_tabs = not options.get("insertSpaces")

        if use_tabs:
            # Indent width doesn't make sense when using tabs
            # the specifications state: "Size of a tab in spaces"
            indent_width = 1

    style_config["USE_TABS"] = use_tabs
    style_config["INDENT_WIDTH"] = indent_width
    style_config["CONTINUATION_INDENT_WIDTH"] = indent_width

    for style_option, value in options.items():
        # Apply arbitrary options passed as formatter options
        if style_option not in style_config:
            # ignore if it's not a known yapf config
            continue

        style_config[style_option] = value

    return style_config

```

[pylsp/plugins/yapf_format.py](https://github.com/python-lsp/python-lsp-server/blob/a3620069a607a63ed52569fde188e9301feae93a/pylsp/plugins/yapf_format.py#L43-L90) · [More projects using YAPF →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20yapf%20for%20source%20formatting%2C%20generated%20modules%20and%20editor%20integrations&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

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

```

From [README.md](https://github.com/google/yapf/blob/main/README.md)

## FAQ

### Which Python formatter should I use?

Use [Ruff](#ruff) for a new project. It formats and lints in one tool, and its formatter is a drop-in replacement for Black. Keep [Black](#black) in projects that already run it, and add [isort](#isort) with the Black profile to sort imports.

### Ruff vs Black: which should I use?

Both give nearly the same output, because Ruff's formatter is a drop-in replacement for Black, but it differs in a few deliberate ways, so pick one and don't alternate. Ruff also lints in the same tool, and its formatter doesn't sort imports, so run `ruff check --select I --fix` before `ruff format`.

### How do I run ruff format?

Run `ruff format` to format every Python file in the current directory. In CI, add `--check` to fail on unformatted files without writing any changes.

### autopep8 vs Black: which should I use?

Use Black to reformat whole files in one opinionated style. Use [autopep8](#autopep) to fix only the problems pycodestyle reports: by default it changes whitespace and leaves the rest of the layout as written.

### YAPF vs Black: which should I use?

Use Black for one fixed style with little to configure. Choose YAPF to match a custom house style through its many style settings, but its last release was in Nov 2024, and it doesn't support some newer Python syntax yet.

## How this page was built

Data checked Nov 18, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python code formatters Black autopep8 YAPF Ruff isort code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
