Skip to the workspace
Pebellslearn by building
Frameworks & Tooling  ›  Lesson

Formatters, Linters and Docs

Code Formatting 19 minA formatter standardizes code layout. A linter flags selected code problems, and documentation explains how code should be used and behave.

A formatter standardizes code layout. A linter flags selected code problems, and documentation explains how code should be used and behave.

Give formatting, diagnostics, type checks, documentation and executable tests distinct jobs in a development workflow.

A beautifully formatted function can still compute the wrong total. Formatting, linting, type checking, tests and documentation each inspect a different part of the program. Give each a clear job, and use a small text-linting exercise to see the difference between detecting a problem and changing the source.

messy code (inconsistent spacing, single quotes, cramped brackets) flowing through black/ruff format into tidy code (consistent spacing, double quotes, one statement per line) — same variable names, same values, same return; only layout changed

Reformat without changing behaviour

black and yapf both rewrite a file's layout to one consistent style. Nothing about what the code does changes — only how it's laid out on the page:

# before
def add(a,b):
  return a+b
x = {'a':1,'b':2}
y=[1,2,  3]

# after `black` (or yapf)
def add(a, b):
    return a + b


x = {"a": 1, "b": 2}
y = [1, 2, 3]

Black deliberately limits style choices (settings include line length, but the point of black is that teams stop arguing about style — there's one answer). yapf predates black and is configurable, closer to a linter's custom rule file than an opinionated "just run it."

Preparing this topic’s interactive investigation…

Catch a bug a formatter would never see

ruff (and its predecessors, flake8/pylint) read the code as a syntax tree, not just text, so they can reason about what names actually exist and get used:

# ruff flags both of these — neither is a formatting issue
import os          # F401: 'os' imported but unused
import json

def greet(name):
    return f"hello {nam}"   # F821: undefined name 'nam' (typo for 'name')
$ ruff check app.py
app.py:1:8: F401 'os' imported but unused
app.py:5:21: F821 undefined name 'nam'
Found 2 errors.

Run the file and the typo doesn't crash until greet is actually called — a code path a quick test might skip entirely. ruff finds it instantly, without running anything, the same way mypy finds a type mismatch (previous section) before the line that has it ever executes.

Document what a function promises

Sphinx builds a project's documentation website directly from docstrings — the comment under def becomes a published page, so the two style conventions below are really about what Sphinx can parse:

def total_price(items, tax_rate):
    """reST style (Sphinx's native format).

    :param items: list of (name, price) tuples
    :param tax_rate: fraction, e.g. 0.18 for 18%
    :returns: the total including tax
    """

def total_price(items, tax_rate):
    """Google style (needs the napoleon extension to parse).

    Args:
        items: list of (name, price) tuples
        tax_rate: fraction, e.g. 0.18 for 18%

    Returns:
        The total including tax.
    """

(A docstring can also hold runnable >>> examples — the doctest module checks those actually produce the output shown. That module itself, and how to run it, belongs with section-17's testing tools; here it's just one more thing a well-documented function might contain.)

quick drill

A formatter and a linter both read your file without running it. What's the real difference in what they're FOR?

Assign each quality check a different question

A formatter can make the wrong formula look consistent. A linter can reject an undefined name while accepting the wrong business rule. A type checker can accept price * quantity even if the required formula includes a fee. Tests and review still need to establish the intended behavior.

For a function that calculates a discounted total, separate the checks:

Check Useful question
formatter is layout consistent with the team's chosen style?
linter are there recognized suspicious patterns or unused names?
type checker do known calls fit the declared types?
test does a concrete boundary input produce the expected amount?
documentation example can a reader predict how to call the public API?

A clean result in one row does not answer the others. Choose a small consistent tool configuration and pin tool versions in the development environment so an upgrade does not unexpectedly reformat the whole project. Review automatic fixes; a linter's unsafe fixes may change behavior and should not be treated like whitespace edits.

The browser lint_lines task is deliberately text-based. It cannot know whether spaces are indentation, literal data inside a multiline string, or harmless formatting. A production formatter parses Python and still needs a reviewed diff. The exercise's trailing-space removal operates on supplied line strings, not arbitrary Python program semantics.

Transfer to documentation: write a docstring for a function that accepts milliseconds, returns a float, and rejects negative values. Include units, one example and the rejection rule. Then change the implementation to accept seconds; identify every caller, test and documentation statement that must change. Sphinx's autodoc can import modules while building docs, so import-time side effects can run during a documentation build too.

References: Ruff fix safety, Black's style, and Sphinx autodoc.

Quick practice

python
What does this print?
def has_trailing_whitespace(line):
    return line != line.rstrip()

print(has_trailing_whitespace("clean"), has_trailing_whitespace("dirty   "))
broken — fix it

It prints 3, but only 2 lines are genuinely too long. Find the line that's wrong before the loop even starts.

What does this print?
lines = ["def f():", "    pass", "", "", "", "x = 1"]
blank_run = 0
flagged = []
for i, line in enumerate(lines, start=1):
    if line.strip() == "":
        blank_run += 1
        if blank_run > 2:
            flagged.append(i)
    else:
        blank_run = 0
print(flagged)

🎯 Your turn

Write lint_lines(lines, max_len=79). Check every line for two problems: too long (len(line) > max_len) and trailing whitespace (line != line.rstrip()). Return a list of [line_number, message] pairs (line numbers starting at 1), in the order you find them — for a line with both problems, report the length issue first.

  • lint_lines(["short", "x" * 85], max_len=79) → [[2, "line too long (85 > 79)"]]
  • A line "dirty " (trailing spaces) → adds [line_number, "trailing whitespace"]

Hint: enumerate(lines, start=1) gives you 1-based line numbers directly; check both conditions for every line and append a message for each one that fires.

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below builds the pieces of a small linter from scratch — and the fix on it that auto-corrects, the way a formatter would.

Your task
Write lint_lines(lines, max_len=79). Check every line for two problems: too long (len(line) > max_len) and trailing whitespace (line != line.rstrip()). Return a list of [line_number, message] pairs (1-based line numbers), length issue first when a line has both. Example: lint_lines(["short", "x" * 85], max_len=79) -> [[2, "line too long (85 > 79)"]].

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upIs this one line too long?

Write is_too_long(line, max_len). Return True if line is longer than max_len characters.

code-quality-tools
DrillDoes this line have trailing whitespace?

Write has_trailing_whitespace(line). Return True if line has any whitespace at the end.

code-quality-tools
BuildCount the blank lines

Write count_blank_lines(lines). Return how many lines are blank (empty, or whitespace-only) after stripping.

code-quality-tools
BossAuto-fix trailing whitespace

Write strip_trailing_whitespace(lines). Return a NEW list with every line's trailing whitespace removed (this is the auto-fix side — what a formatter does instead of just reporting).

code-quality-tools
CapstoneA fuller lint pass

Write full_lint(lines, max_len=79). Combine three checks: line too long, trailing whitespace, and — new — more than 2 CONSECUTIVE blank lines (flag the line where the run goes past 2). Return [line_number, message] pairs in the order the checks are listed, for each line, in line order.

code-quality-tools
Project context and further resources
lint_lines.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
lint_lines(lines, max_len) → listReport [line_number, message] for every line that's too long or has trailing whitespace.
try:
returned
No app map for this section yet.
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.