Python's Style Guidelines, Concise Summary

© 2008, Martin Rinehart

This page summarizes the Python style guidelines in PEP 8 (authors: Guido van Rossum and Barry Warsaw). As is appropriate for a style guideline, that document includes reasons for its recommendations and examples of good and bad style. This is strictly a summary document. Its target audience is the programmer who has read, but not memorized, PEP 8.

Naming Conventions

lower (lowercase, and short):   packages, modules
lower_and_underscores: functions, global variables
UpperAndLower: classes
Note: These are all public. Any of them may be prefixed with '_' for a non-public. Use double-underscore prefix for name mangling in classes designed for subclassing. Use single-underscore suffix to avoid Python reserved words. Use __xxx__ only as documented. Don't use letter 'O' and numeral zero where they could be confused. Ditto for 'i', 'l' and numeral one.

On Style Guidelines

"Readability counts."
Guidelines promote consistency. Consistency promotes readability.
"A foolish consistency is the hobgoblin of little minds." Break rules if it improves readability.
Module written to other rules? Be consistent within module (if module too long or time too short to make module consistent with guidelines).
General Coding
Maximum line length 79 (72 in long blocks of text).
Line wrapping Within '()', '[]' or '{}' preferred; '\' OK.
Line continuation indent [ed.: inferred from examples] One space after opening '(' or indented 3 spaces (3 more than suite) following '\'.
Encodings Latin-1 before Python 3.0. UTF-8 for 3.0 and later.
Identifiers English words whenever possible. Exceptions: test cases for non-ASCII; author's names. (Authors must provide Latin transliteration for names).
Comments and Docstrings
Comments Never inaccurate! Complete sentences. Identifiers capitalized per code. Two spaces after periods. Strunk and White style. Write in English.
Inline comments Sparingly, separated by two or more spaces; starting '# '. Don't restate code. Do explain why code needed.
Docstrings Include for all public modules, functions, classes, methods. Non-public methods should have comment explaining purpose after 'def' line. Excepting one-liners, closing '"""' should be on separate line.
Naming Formatting Other
Packages lower
Modules lower
Blank Lines
2 Between funcs and classes
1 Between methods
2 Between groups of funcs (sparingly)
0 Between one-liner funcs
Version control 'crud': docstring, blank line, crud, blank, code.
Use __all__ mechanism if intended use is from mod import *.
Imports n/a Location: just after module docstring [and version crud].
Order: blank line,standard library, blank, third party, blank, local, blank, [__all__ specs, blank]
One module per line.
Use absolute (not relative) import specs.
Import module, not names, to avoid name conflicts.
Module Data globals: lower_and_underscores
'_' prefix for non-public
Module "Constants"
Functions lower_and_underscores
'_' prefix for non-public
Blank lines, sparingly, between sections.
Parameters
Other Function Variables
Classes (including Exceptions) UpperAndLower Note: no more string exceptions. Classes only.
Use suffix 'Error' on exceptions (if they are errors).
Class Methods cls is first arg.
Class Variables
Class Instances
Class Instance Methods Use non-publics in preference to publics. self is first arg. Expose names, not accessor/mutator functions. Use properties as needed. Use double leading underscores (name mangling) to avoid name conflicts when subclassing is intended.
Class Instance Variables
Suites n/a Indent four spaces. (Use /t and /tt for old code.)
Block comments indented to level of following code.
Paragraphs within block comments: a single '#'.
Statements n/a Compound statements generally discouraged.
Use suites after ':' except for tiny things.
raise SomeError('message')
except SomeError[, OtherError]: # use specific error(s)
try: ... finally: better than bare except:.
Minimize code after try:.
Expressions n/a
Using Spaces
Yes No
Around binary operators.
Around [augmented] assignments.
Around '=' in argument/parameter lists.
Inside parens, brackets, braces.
Before ':'.
Between function name and argument/parameter list.
To align assignments.
Use ''.join() to concatenate strings.
Comparisons to singletons (None) should be is [not].
Don't use if x when you mean if x is not None.
Use string methods, not string functions.
Use x.startswith() and x.endswith(), not slicing.
(See PEP 8 for strings, Python 2.3 and earlier.)
Use isinstance() instead of type comparisons.
Don't use trailing whitespace at end of string literals.