Skip to content

Module 19 · Debugging, Testing and Best Practices — topic 10 of 15

PEP 8

Python's official style guide: indentation, line length, blank lines, imports, whitespace, naming, and comparisons — plus formatters and linters (black, ruff) that apply it automatically.

Beginner 8 min read·Lesson 288 of 306 in Python Programming

Learning objectives

  • Apply the main PEP 8 rules
  • Recognise common style problems
  • Use tools that check and format code automatically

Definition

PEP 8 is the official style guide for Python code. It defines conventions for layout, whitespace, naming and other details so that Python code looks consistent and is easy to read across projects.

Introduction

Code is read far more often than it is written. When everyone follows the same style, any Python file feels familiar.

Why it matters

Consistent style removes distractions in code review and makes it easier to spot real problems. Most teams enforce PEP 8 automatically.

Detailed explanation

Indent with 4 spaces, never tabs.

Limit lines to 79 characters (many projects use 88 or 99); break long expressions inside parentheses.

Two blank lines around top-level functions and classes; one blank line between methods.

Imports at the top, one per line, grouped: standard library, third-party, local — separated by blank lines.

Spaces around operators and after commas (x = a + b, f(a, b)), but not inside brackets or before a function call's parenthesis.

Naming: snake_case for functions and variables, PascalCase for classes, UPPER_CASE for constants, _leading_underscore for internals.

Compare to None with is, write if items: rather than if len(items) > 0:, and use isinstance() rather than comparing types.

Formatters (black, ruff format) rewrite code into a consistent style; linters (ruff, flake8, pylint) report style and likely bugs. Editors can run them on save.

Syntax

Python
import os
import sys
import requests
from app import utils
MAX_RETRIES = 3
class OrderService:
def place_order(self, item_id, quantity=1):
if quantity <= 0:
raise ValueError("quantity must be positive")
return {"item": item_id, "qty": quantity}
  • 4 spaces, short lines.
  • Grouped imports.
  • Standard naming styles.

Code examples

Same behaviour, better style

Python
def CalcArea( W,H ):return W*H
def calc_area(width, height):
return width * height
print(CalcArea(3,4) == calc_area(3, 4))
Output
True

Both work identically; only the second is easy to read and follows PEP 8.

Formatting and linting tools

Terminal
python -m pip install ruff
python -m ruff check . # report style problems and likely bugs
python -m ruff format . # rewrite files in a consistent style

More examples

A tiny style checker

Python
source = "def f(x):\n\treturn x \nname = 'ok'\nvery_long_line = '" + "x" * 80 + "'\n"
for n, line in enumerate(source.splitlines(), 1):
problems = []
if len(line) > 79:
problems.append(f"line too long ({len(line)} > 79)")
if line != line.rstrip():
problems.append("trailing whitespace")
if "\t" in line:
problems.append("tab indentation")
if problems:
print(n, ", ".join(problems))
Output
2 trailing whitespace, tab indentation
4 line too long (99 > 79)

Step-by-step explanation

  • The source text contains three classic style problems.
  • Each line is checked for length, trailing whitespace and tabs.
  • Real linters check hundreds of such rules in the same way.

Expected output

Running “A tiny style checker” prints exactly:

TextOutput
2 trailing whitespace, tab indentation
4 line too long (99 > 79)

Practical applications

  • Pre-commit hooks that format code before every commit.
  • CI pipelines that fail when linting fails.

Best practices

  • Let a formatter handle layout.
  • Run a linter in your editor.
  • Follow the project's existing style when it differs.

Common mistakes

Mixing tabs and spaces

Avoid

def f():
if x:
return 1

Prefer

def f():
if x:
return 1

Python 3 rejects inconsistent indentation with TabError.

Important notes

  • PEP 8 itself says consistency within a project matters more than any single rule.

Key takeaways

  • PEP 8 is Python's style guide.
  • 4 spaces, short lines, grouped imports, standard naming.
  • Formatters and linters apply it automatically.

Try it yourself

  1. 1
    Run ruff on one of your earlier programs and fix the reported issues.
  2. 2
    Rewrite a badly formatted function to follow PEP 8 by hand.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedAccording to PEP 8, which naming style is used for classes?
Practise this topic