Python Type Hints and Code Quality · Lesson 135 of 149

Python PEP 8 and Formatting Tools

What you will learn

  • What PEP 8 is and why consistent style matters
  • Naming conventions, spacing, imports, comparisons
  • Linters and formatters: what each does
  • Using ruff and black and reading their reports
  • Configuring them in pyproject.toml
  • Checking style before every commit

1. Why style matters

Code is read far more often than it is written. Programs with the same layout, names and habits are easier to read, review and fix, especially when many people work on them. PEP 8 ("Python Enhancement Proposal 8") is Python's official style guide. It is not a law of the language: code with bad style still runs. But following it makes your code look like everyone else's, and tools can check it automatically.

Two kinds of tool help:

Tool kind What it does Examples
formatter rewrites your code's layout (spacing, line breaks, quotes) black, ruff format
linter finds likely bugs and style problems and tells you ruff check, flake8, pylint

A formatter changes the file; a linter only reports (though many problems can be auto-fixed). The type checker from lessons 19.1 and 19.2 is a third kind of tool. Together they catch many problems before the code runs.

2. PEP 8 in brief

Names

Thing Style Example
variables, functions, methods, modules lower_case_with_underscores total_price, calculate_total
classes CapWords Greeter, HttpClient
constants UPPER_CASE MAX_RETRIES
"private" names leading underscore _helper, _cache
avoid one-letter l, O, I (look like digits)

Names should say what the thing is (total, not t), and not clash with built-ins (lesson 18.6).

Layout

  • Four spaces per indentation level, never tabs mixed with spaces.
  • Line length: PEP 8 says 79 characters; many teams (and the black formatter) use 88, others up to 100. Pick one and let the tool enforce it.
  • Two blank lines between top-level functions and classes, one between methods.
  • Spaces around operators (a = b + c), none inside brackets (f(x), not f( x )), none before a comma or colon, one after.
  • No spaces around = for keyword arguments and defaults: f(x, tax=0.1).
  • One statement per line: if ok: print("ok") on one line is discouraged.

Imports

  • At the top of the file, one per line (import os then import sys, not import os, sys).
  • Three groups separated by a blank line: standard library, third-party, your own modules; sorted within each (lesson 16.1).
  • Avoid from module import * (lesson 16.1).

Comparisons and comments

  • Compare to None with is / is not: if x is None:, never x == None (lesson 18.6).
  • Use truthiness for emptiness checks: if items: rather than if len(items) > 0: (lesson 5.3).
  • Use def for named functions, not name = lambda ....
  • Docstrings for modules, classes and public functions; comments explain why, not what; keep them up to date (lesson 19.4).
Quick check: which is PEP 8 style: `calculateTotal`, `CalculateTotal` or `calculate_total`?

calculate_total for a function. (CalculateTotal would be a class name.)

3. A messy file

Here is working code written carelessly (messy.py):

import os, sys
import json
from collections import *

def  CalculateTotal( items,tax = 0.2 ):
    Total=0
    for i in items :
        Total+=i['price']*i["qty"]
    l = lambda x: x*2
    if Total == None:
        return 0
    unused = 5
    return Total*(1+tax)

class my_class:
    def __init__(self,name):
        self.name=name
    def Greet(self ):
        print("Hello, "+self.name+"!")

result = CalculateTotal([{'price':10,'qty':2},{'price':5,'qty':1}] , tax=0.1)
print( result )
x = [1,2,3,
  4,5]
if result > 5 and result < 100 : print("ok")

It runs, but it is hard on the eyes and hides problems.

4. ruff: linter and formatter

ruff is a fast tool that does both jobs (it replaces older tools such as flake8, isort and black). Install it into the project's environment (lessons 16.5 and 16.6):

python -m pip install ruff

Linting: ruff check

python -m ruff check messy.py

By default ruff enables a small, safe set of rules. Choosing more rule groups with --select (E and W are PEP 8 style errors and warnings, F is the "pyflakes" group of real bugs, I is import sorting, N is naming, B is likely bugs, UP suggests modern syntax) gave this report for messy.py (ruff 0.17.1):

messy.py:1:1: E401 [*] Multiple imports on one line
messy.py:1:1: I001 [*] Import block is un-sorted or un-formatted
messy.py:1:8: F401 [*] `os` imported but unused
messy.py:1:12: F401 [*] `sys` imported but unused
messy.py:2:8: F401 [*] `json` imported but unused
messy.py:3:1: F403 `from collections import *` used; unable to detect undefined names
messy.py:5:6: N802 Function name `CalculateTotal` should be lowercase
messy.py:6:5: N806 Variable `Total` in function should be lowercase
messy.py:8:9: N806 Variable `Total` in function should be lowercase
messy.py:9:5: E741 Ambiguous variable name: `l`
messy.py:9:5: E731 Do not assign a `lambda` expression, use a `def`
messy.py:9:5: F841 Local variable `l` is assigned to but never used
messy.py:10:17: E711 Comparison to `None` should be `cond is None`
messy.py:12:5: F841 Local variable `unused` is assigned to but never used
messy.py:15:7: N801 Class name `my_class` should use CapWords convention
messy.py:18:9: N802 Function name `Greet` should be lowercase
messy.py:25:32: E701 Multiple statements on one line (colon)
Found 17 errors.
[*] 5 fixable with `--fix` (4 unsafe fixes available with `--fix --unsafe-fixes`).

Each line is file:line:column: CODE message. The code (such as F401) can be looked up in ruff's documentation. [*] marks problems that ruff can fix itself with --fix. The "unsafe" fixes might change behaviour (for example, deleting an unused variable whose right-hand side has an effect), so review them.

Notice that a linter finds real problems, not just style: unused imports (F401), unused variables (F841), and a comparison Total == None (E711) that should use is.

Formatting: ruff format or black

python -m ruff format messy.py
python -m black messy.py

Both rewrite the file. ruff format --diff (or black --diff) shows the changes without making them, and --check only reports whether the file would change (useful in automated checks). The formatter fixed spacing, line breaks, quotes and blank lines, for example:

-def  CalculateTotal( items,tax = 0.2 ):
-    Total=0
-    for i in items :
-        Total+=i['price']*i["qty"]
+def CalculateTotal(items, tax=0.2):
+    Total = 0
+    for i in items:
+        Total += i["price"] * i["qty"]

A formatter does not rename things or remove unused code; that is the linter's and your job. The big advantage of a formatter is that style discussions end: the tool decides, and everyone's code looks the same.

5. The cleaned file

After fixing the names, removing the unused code, using is-style comparisons, a chained comparison (lesson 5.6) and adding docstrings (clean.py):

"""Order totals."""


def calculate_total(items, tax=0.2):
    """Return the total of all items including tax."""
    total = 0
    for item in items:
        total += item["price"] * item["qty"]
    if total == 0:
        return 0
    return total * (1 + tax)


class Greeter:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print("Hello, " + self.name + "!")


result = calculate_total([{"price": 10, "qty": 2}, {"price": 5, "qty": 1}], tax=0.1)
print(result)
numbers = [1, 2, 3, 4, 5]
if 5 < result < 100:
    print("ok")

The checks on this file:

ruff check (E, F, W, N, I, B, UP, D100, D103):  All checks passed!
ruff format --check:   1 file already formatted
black --check:         1 file would be left unchanged.

and it runs, printing 27.500000000000004 (the usual floating-point tail, lesson 3.4) and ok. (The rules D100 and D103 ask for module and function docstrings.)

6. Configuring the tools

Put settings in the project's pyproject.toml so that everyone, and the automated checks, use the same ones:

[tool.ruff]
line-length = 88
target-version = "py312"

[tool.ruff.lint]
select = ["E", "F", "W", "I", "N", "B", "UP"]
ignore = ["N802"]

[tool.ruff.format]
quote-style = "double"

[tool.black]
line-length = 88

[tool.mypy]
python_version = "3.13"
strict = false
warn_unused_ignores = true

With this file in place, ruff check reported 15 problems instead of 17 on the same messy file, because N802 (function names) is now ignored. Other useful settings: exclude for folders, per-file ignores for tests, and extend-select. Add # noqa: F401 at the end of a line to silence one rule on that line (use rarely).

Use either ruff format or black, not both; they produce nearly identical results, and ruff is faster.

7. Making it a habit

When How
while typing the editor shows linter warnings and formats on save (VS Code, PyCharm)
before each commit run ruff check, ruff format --check and mypy (and the tests, lesson 18.2)
automatically a pre-commit hook runs them on every git commit (the pre-commit tool)
on the shared repository a continuous-integration job runs the same commands on each push, so nothing unchecked is merged

A reasonable minimum workflow: python -m ruff format ., then python -m ruff check ., then python -m mypy ., then python -m pytest. Fix what they report, then commit.

Do not apply a formatter to an existing project in the middle of other work: make one commit that only formats, so that real changes stay easy to review.

Worked example: from messy to clean

Starting from messy.py above, the steps and what each tool contributed:

Step Command Result
1. lint ruff check messy.py --select E,F,W,N,I,B,UP 17 reports: style, naming, unused code, == None, a lambda assignment, wildcard import
2. format (preview) ruff format --diff messy.py spacing, quotes, blank lines, line breaks fixed: the file "would be reformatted"
3. hand edits rename CalculateTotal → calculate_total, Total → total, my_class → Greeter, Greet → greet; delete unused imports and variables; replace == None with a sensible test; use a chained comparison; add docstrings the file clean.py
4. re-check ruff check, ruff format --check, black --check all pass
5. run python clean.py 27.500000000000004 and ok

One edit deserves a comment: the original test if Total == None could never be true (a sum is a number), so it was dead code. The cleaned version checks total == 0 instead, to return early for an empty order. A linter found the style fault, but deciding what the code should do was a human job. After large changes like this, run the tests (lesson 18.2): in this example the printed result is unchanged, which is a quick sign that behaviour was kept.

The order data is made up.

Common mistakes

  • Fighting the formatter with endless exceptions; accept its choices.
  • Running a formatter and a linter with conflicting settings.
  • Silencing warnings with noqa or type: ignore instead of fixing them.
  • Formatting in the same commit as real changes.
  • Never running the tools, so style drifts.
  • Using two different formatters in one project.
  • Believing style tools replace tests; they catch layout and some bugs, not wrong logic.
  • Line-length wars: choose a number once, in the config.

Key takeaways

  • PEP 8 is Python's style guide: snake_case for functions and variables, CapWords for classes, UPPER_CASE for constants, four-space indents, tidy imports, is None.
  • A formatter (ruff format, black) rewrites layout; a linter (ruff check) reports problems, including real bugs such as unused imports and variables.
  • Configure rules and line length once in pyproject.toml.
  • Run the formatter, linter, type checker and tests before each commit, ideally automatically.
  • Tools settle style arguments; they cannot decide what your code should do.

Practice

1. Rename these to PEP 8 style: function GetUserName, class user_account, constant maxRetries.

Show answer

get_user_name, UserAccount, MAX_RETRIES.

2. What is the difference between a linter and a formatter?

Show answer

A formatter rewrites the layout of your code; a linter reports problems (style and likely bugs) without necessarily changing anything.

3. Why write if x is None rather than if x == None?

Show answer

None is a single object, so identity is the correct and safest test; == can be overridden by a class and is flagged by linters.

4. Where do you put shared settings for ruff, black and mypy?

Show answer

In the project's pyproject.toml, under [tool.ruff], [tool.black] and [tool.mypy].

5. What does ruff format --check do?

Show answer

It reports whether files would be reformatted, without changing them; useful in automated checks.

6. Why make a formatting-only commit when adopting a formatter?

Show answer

So that the large, mechanical changes do not hide real changes, and reviewers can skim the formatting commit and focus on the rest.