Python (PEP 8) — Claude Code rules
Write Python that follows PEP 8 (style) and PEP 257 (docstrings). PEP 8's own guidance applies: code is read more often than written, and consistency within a module or function matters most. Know when to be inconsistent — don't break backward compatibility just to comply.
Run a formatter (e.g.
blackorruff format) and a linter (ruff/flake8) so layout is enforced mechanically, not by hand. These rules describe the target; the formatter gets you there.
Layout
- 4 spaces per indentation level. Spaces, never tabs (tabs only to stay consistent with already-tab-indented code).
- Limit lines to 79 characters (72 for docstrings and comments). Teams may agree on up to 99 for code, but keep comments/docstrings at 72.
- Two blank lines around top-level function and class definitions; one blank line between methods inside a class. Blank lines sparingly inside functions to separate logical sections.
- No trailing whitespace.
- Break long expressions before a binary operator, not after.
Whitespace in expressions
- No spaces just inside
(),[],{}, and none before,,;,:or a call/index bracket:spam(ham[1], {eggs: 2}). - Surround binary operators with a single space (
=,==,<,+=,and,or,not,is). - No spaces around
=for keyword args / unannotated defaults (f(real, imag=0.0)), but add them when an annotation is present (def f(sep: str = "")). - In slices treat
:as a binary operator with even spacing (ham[lower:upper]).
Naming
- Functions, variables, methods, modules:
snake_case. Modules/packages stay short and all-lowercase. - Classes, type variables, exceptions:
CapWords(exceptions end inError). - Constants (module level):
UPPER_CASE_WITH_UNDERSCORES. _single_leading_underscorefor non-public/internal;__double_leadingonly to invoke name mangling;trailing_underscore_to dodge a keyword (e.g.class_). Never name anythingl,O, orI.- First method args are
self(instance) andcls(class).
Imports
- One import per line (
import osthenimport sys);from x import a, bis fine. - Imports at the top of the file, after the module docstring, before globals.
- Group as (1) standard library, (2) third-party, (3) local, one blank
line between groups. Prefer absolute imports. No wildcard
from x import *.
Docstrings & comments (PEP 257)
- Docstrings for every public module, function, class, and method (including
__init__). Always"""triple double quotes"""(r"""..."""if it needs backslashes). - One-liner: text and closing
"""on the same line, imperative mood ("Return the path", not "Returns the path"), ends with a period. - Multi-line: summary line, blank line, then the body; closing
"""on its own line. Blank line after a class docstring before its methods. - Block comments at code indent, each line
#then text, complete sentences. Inline comments: at least two spaces before#, used sparingly.
Comparisons
- Compare to
Nonewithis/is not, never==. Useis not x, notnot ... is. - Don't compare booleans with
==; writeif greeting:notif greeting == True. - Use
isinstance(obj, int), nottype(obj) is int. - Lean on truthiness for empty sequences:
if not seq:/if seq:.
Type hints (PEP 484, optional)
- Annotate with
def f(x: int) -> str:; import constructs fromtyping. - Use
Optional[T](orT | None) whenNoneis allowed. - Hints are static-analysis only — not enforced at runtime.
Don't
- Don't mix tabs and spaces, or exceed the line limit without team agreement.
- Don't use a bare
except:; catch specific exceptions and keeptryblocks small. - Don't bind a lambda to a name — use
def. - Don't write comments that contradict the code; update or delete them.