Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Linting, Types and Formatting

Formatting with Black and Ruff Format

End style debates with an automatic Python formatter. Run Black for real, learn the magic trailing comma and line length, and configure Black or ruff format.

Few topics waste as much team time as code layout: single or double quotes, where to break a long call, how many blank lines. An autoformatter ends the debate. It rewrites your code into one consistent layout every time, so reviews can focus on logic and diffs never contain "fixed spacing" noise.

Black popularized the idea in Python with its promise of being "uncompromising": there are very few options, and the output is the same no matter who wrote the input. Ruff format is a much faster formatter that is designed to produce almost identical output. This lesson shows what a formatter does, runs Black for real, and explains how to set it up.

Linter versus formatter

They overlap a little, but they have different jobs:

Linter Formatter
Question "Is this code probably wrong or unwise?" "How should this code be laid out?"
Changes meaning? May suggest it Never (the program behaves the same)
Output A list of findings The rewritten file
Examples Ruff check, pyflakes Black, ruff format

A formatter never changes what your program does. It only changes whitespace, line breaks, quotes and parentheses, and it verifies that the syntax tree before and after is equivalent.

Black in action

Here is Black running for real on deliberately ugly code:

Python Format messy code with Black

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare the two versions: quotes became double quotes, spaces were normalized around operators and commas, blank lines were added between definitions, and the one-line __init__ with semicolons was split into separate statements. Black also left import os, sys on one line: it fixes spacing but does not split or sort imports. That is the job of a linter such as Ruff (I rules, or the older isort).

Line length

Black wraps code that does not fit in the line length (88 characters by default). Change it with line_length:

Python Line length and the magic trailing comma

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two behaviors are worth noticing. First, when a call does not fit, Black first tries to move all arguments onto one indented line; if that is still too long, it puts one argument per line and adds a trailing comma. Second, the magic trailing comma: a collection that already ends in a comma stays exploded, one item per line, even if it would fit. pair keeps its vertical layout while other stays compact. You control the layout by adding or removing that final comma, and diffs stay small because adding an item changes only one line.

Checking instead of rewriting

In CI you usually do not want to rewrite files; you want to fail if they are not formatted. The command-line flags are:

Terminal
black .                 # rewrite files
black --check .         # exit code 1 if anything would change
black --diff .          # show what would change

You can reproduce the check logic with the API:

Python A format check like black --check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that a file with a syntax error cannot be formatted. Black refuses rather than guessing.

Configuration

Black reads [tool.black] from pyproject.toml:

TOML
[tool.black]
line-length = 88
target-version = ["py311"]
extend-exclude = '''
/(
  migrations
  | build
)/
'''

Resist the urge to configure much. Every option you add is another thing for the team to learn, and the point of Black is that it just works. The single most common change is line-length, and it should match your linter's setting so the two tools do not disagree.

Ruff format

If you already use Ruff for linting, ruff format can replace Black with one fewer dependency and much higher speed:

Terminal
ruff format .             # rewrite files
ruff format --check .     # CI mode
TOML
[tool.ruff]
line-length = 88

[tool.ruff.format]
quote-style = "double"
indent-style = "space"
docstring-code-format = true   # also format code inside docstrings

Ruff's formatter targets Black's style and agrees with it on the vast majority of code, with a small number of documented differences. Pick one tool per project and do not run both.

When you adopt a formatter on an existing project, run it once on everything in a single commit that does nothing else. Add that commit's hash to a .git-blame-ignore-revs file (and run git config blame.ignoreRevsFile .git-blame-ignore-revs) so git blame still shows the real authors of each line.

Sorting imports

Black does not reorder imports. Use Ruff's I rules (a replacement for isort) and let the formatter handle the rest:

Terminal
ruff check --select I --fix .
ruff format .

This order matters: sort imports first, format second, because sorting can change line lengths.

Editor and workflow tips

  • Turn on format on save in your editor so you never see unformatted code.
  • Put the formatter in a pre-commit hook so unformatted code cannot be committed.
  • Run the --check variant in CI as the final safety net.
  • Use # fmt: off and # fmt: on around a block you deliberately format by hand, such as an aligned lookup table. Use it rarely.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a formatter guarantee about your program?

    A formatter changes whitespace, wrapping, quotes and parentheses while preserving the meaning of the code, and Black even checks the syntax trees are equivalent.
  2. 2. What is Black's "magic trailing comma"?

    If you write a trailing comma, Black keeps the one-item-per-line layout even if the collection would fit on one line, which keeps diffs small.
  3. 3. Which command makes CI fail when files are not formatted, without changing them?

    --check returns a non-zero exit status if any file would be reformatted, and leaves the files alone.
  4. 4. Why run the formatter in one dedicated commit when adopting it?

    A single formatting-only commit keeps history readable, and .git-blame-ignore-revs hides it from blame output.

Summary

  • A formatter rewrites layout consistently and never changes behavior; a linter finds problems.
  • Black has almost no options, wraps at 88 characters by default, and honors the magic trailing comma.
  • black --check or ruff format --check is the CI form; ruff format is a faster near-drop-in alternative.
  • Sort imports with Ruff's I rules before formatting.
  • Adopt a formatter in one isolated commit and automate it in the editor, pre-commit and CI.

Next: Type Checking with mypy