Python Reference ยท Practical Pages
PEP 8 style guide
The PEP 8 rules in practice: naming conventions, indentation, line length, imports, whitespace, comparisons, docstrings and the tools that enforce them.
PEP 8 is the community style guide for Python code. It does not change how a program runs. It exists so that code written by different people looks alike, which makes it easier to read, review and maintain. Most teams follow it, usually with a formatter that applies the mechanical parts automatically.
The guide is advice, not law. Its own opening principle is that consistency within a project matters more than strict agreement with the guide, and that you may break a rule when following it would make the code harder to read. The sections below summarize the rules you will meet most often, in our own words.
def average(values): return sum(values) / len(values)
Try it
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.
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.
The main rules
Layout
- Indent with 4 spaces per level. Never mix tabs and spaces.
- Keep lines to about 79 characters (72 for comments and docstrings). Many teams relax this to 88 or 100 and agree on it with a formatter.
- Separate top-level functions and classes with two blank lines, and methods inside a class with one.
- Break long lines inside brackets, not with backslashes. Put the binary operator at the start of the new line.
- End files with a single newline.
Imports
- One import per line (
from x import a, bis fine). - Put imports at the top of the file, grouped in this order, with a blank line between groups: standard library, third-party packages, your own modules.
- Prefer absolute imports. Avoid
from module import *, because it hides where names come from.
Whitespace
- Spaces around operators and after commas:
x = a + b,f(1, 2). - No spaces just inside brackets (
spam(ham[1])), before a comma, or before the parenthesis of a call. - No spaces around
=for keyword arguments and defaults:def f(size=10). With a type annotation, do use them:def f(size: int = 10). - Do not align assignments with extra spaces; it creates noisy diffs.
- No trailing whitespace at the end of a line.
Naming
| Kind | Style | Example |
|---|---|---|
| Variables, functions, methods, modules | snake_case |
user_name, load_data() |
| Classes and exceptions | CapWords |
HttpClient, ValidationError |
| Constants | UPPER_SNAKE_CASE |
DEFAULT_TIMEOUT |
| Internal use | leading underscore | _helper |
| Avoid clashing with a keyword | trailing underscore | class_ |
| Type variables | short CapWords |
T, KeyType |
Avoid single-character names l, O and I; they look like digits.
Comments and docstrings
- Write complete sentences and keep comments accurate. A wrong comment is worse than none.
- Explain why, not what the code obviously does.
- Give every public module, class and function a docstring in triple double quotes, with a one-line summary first.
Programming recommendations
- Compare to singletons with
isandis not(if x is None), not==. - Prefer
if items:overif len(items) > 0:. - Write
if x is not None, notif not x is None. - Use
defrather than assigning a lambda to a name. - Catch specific exceptions; a bare
except:also hidesKeyboardInterrupt. - Keep
tryblocks small, and usewithfor files and locks. - Use
isinstance()instead of comparingtype()values. - Be consistent in return statements: either every path returns a value (even
Noneexplicitly) or none do.
Tools
| Tool | What it does |
|---|---|
ruff |
A very fast linter and formatter that covers the PEP 8 checks and many more. |
black |
An opinionated formatter: no options to argue about, 88-character lines by default. |
flake8 / pycodestyle |
Report style violations without changing files. |
isort |
Sorts and groups imports (also available as a ruff rule set). |
mypy, pyright |
Type checkers, which cover correctness rather than layout. |
Usage notes
- Let a formatter do the work. Run it automatically on save or in a pre-commit hook, so style never comes up in code review.
- Do not reformat code you are not changing. Style-only edits make history hard to read; do them in a separate commit.
- The line-length limit is the most debated rule. Whatever number you choose, put it in the project configuration (
pyproject.toml) so everyone shares it. - The standard library itself does not follow every rule. Old modules use names like
getLoggerandunittest.TestCase.assertEqual; match the library you are calling. - Style is not correctness. A tidy program can still be wrong. Combine style tools with tests and type checks.
Related
typing,dataclasses,doctest- Lessons: Syntax, Variables, Pythonic code