PEP 8 Style Guide
PEP 8 is Python's official style guide — "PEP" stands for Python Enhancement Proposal, the process the language uses to propose and document changes and conventions. PEP 8 specifically covers how Python code should look: indentation, naming, spacing, import order, and dozens of smaller conventions. It was written by Guido van Rossum (Python's creator) and others precisely because code is read far more often than it is written, and a shared style makes any Python codebase easier for anyone to jump into.
PEP 8 is not enforced by the interpreter — you can ignore every rule in it and your code will still run. It is a social contract for readability, and the vast majority of the Python community and tooling ecosystem (linters, formatters, code review norms) assumes you are following it.
The key rules
Rule | Guideline |
|---|---|
Indentation | 4 spaces per level, never tabs |
Line length | 79 characters in strict PEP 8; many modern teams relax this to 88-99 with tools like |
Variables & functions |
|
Classes |
|
Constants |
|
Blank lines | Two blank lines between top-level functions/classes; one blank line between methods inside a class |
Import order | Standard library imports, then third-party, then local — each group separated by a blank line |
Import ordering example
# 1. Standard library import os import sys from datetime import datetime # 2. Third-party import requests from flask import Flask # 3. Local application from myapp.models import User from myapp.utils import slugify
Naming conventions in practice
MAX_CONNECTIONS = 10 # constant: UPPER_CASE
class HttpClient: # class: PascalCase
def send_request(self): # function/method: snake_case
retry_count = 0 # variable: snake_case
return retry_countLet tools do the enforcing
In practice, almost nobody manually checks their code against the PEP 8 document line by line. Two tools have made that unnecessary:
black— an opinionated auto-formatter. It rewrites your code to a consistent style (line length, quote style, spacing) with no configuration debates; you run it and your code is compliant.ruff— an extremely fast linter (and increasingly, formatter) that flags PEP 8 violations, unused imports, and dozens of other issues, and can auto-fix many of them withruff check --fix.
pip install black ruff black . # reformat every file in the project ruff check . # lint for style and correctness issues ruff check --fix . # auto-fix what can be auto-fixed
Why it matters
Consistent style is not about aesthetics for their own sake. When every file follows the same conventions, your eyes don't have to re-adjust to a new visual language every time you open a different module, code review can focus on logic instead of formatting nitpicks, and diffs stay small and meaningful because a formatter isn't fighting a human's manual spacing choices.