PEP 8_ the Style Guide for Python Code
PEP 8_ the Style Guide for Python Code
Introduction
This document gives coding conventions for the Python
code comprising the standard library in the main Python
distribution. Please see the companion informational PEP
describing style guidelines for the C code in the C
implementation of Python 1.
Code lay-out
Indentation
Use 4 spaces per indentation level.
Yes:
# Aligned with opening delimiter.
foo·=·long_function_name(var_one,·var_two,
·························var_three,·var_four)
No:
Optional:
# No extra indentation.
if·(this_is_one_thing·and
····that_is_another_thing):
····do_something()
my_list·=·[
····1,·2,·3,
····4,·5,·6,
····]
result·=·some_function_that_takes_arguments(
····'a',·'b',·'c',
····'d',·'e',·'f',
····)
my_list·=·[
····1,·2,·3,
····4,·5,·6,
]
result·=·some_function_that_takes_arguments(
····'a',·'b',·'c',
····'d',·'e',·'f',
)
Tabs or Spaces?
Spaces are the preferred indentation method.
with·open('/path/to/some/file/you/want/to/read
·····open('/path/to/some/file/being/written',·
····file_2.write(file_1.read())
Blank Lines
Surround top-level function and class definitions with
two blank lines.
Imports
Imports should usually be on separate lines, e.g.:
Yes:
import·os
import·sys
No:
import·os,·sys
from·subprocess·import·Popen,·PIPE
Imports are always put at the top of the file, just after
any module comments and docstrings, and before
module globals and constants.
import·mypkg.sibling
from·mypkg·import·sibling
from·mypkg.sibling·import·example
from·.·import·sibling
from·.sibling·import·example
from·myclass·import·MyClass
from·foo.bar.yourclass·import·YourClass
import·myclass
import·foo.bar.yourclass
For example:
from·__future__·import·barry_as_FLUFL
__all__·=·['a',·'b',·'c']
__version__·=·'0.1'
__author__·=·'Cardinal Biggles'
import·os
import·sys
String Quotes
In Python, single-quoted strings and double-quoted
strings are the same. This PEP does not make a
recommendation for this. Pick a rule and stick to it. When
a string contains single or double quote characters,
however, use the other one to avoid backslashes in the
string. It improves readability.
Whitespace in
Expressions and
Statements
Pet Peeves
Avoid extraneous whitespace in the following situations:
Yes:
spam(ham[1],·{eggs:·2})
No:
spam(·ham[·1·],·{·eggs:·2·}·)
Yes:
foo·=·(0,)
No:
bar·=·(0,·)
Yes:
if·x·==·4:·print·x,·y;·x,·y·=·y,·x
No:
if·x·==·4·:·print·x·,·y·;·x·,·y·=·y·,·x
ham[1:9],·ham[1:9:3],·ham[:9:3],·ham[1::3]
ham[lower:upper],·ham[lower:upper:],·ham[l
ham[lower+offset·:·upper+offset]
ham[:·upper_fn(x)·:·step_fn(x)],·ham[::·st
ham[lower·+·offset·:·upper·+·offset]
No:
ham[lower·+·offset:upper·+·offset]
ham[1:·9],·ham[1·:9],·ham[1:9·:3]
ham[lower·:·:·upper]
ham[·:·upper]
Yes:
spam(1)
No:
spam·(1)
Yes:
dct['key']·=·lst[index]
No:
dct·['key']·=·lst·[index]
Yes:
x·=·1
y·=·2
long_variable·=·3
No:
x·············=·1
y·············=·2
long_variable·=·3
Other Recommendations
Avoid trailing whitespace anywhere. Because it’s
usually invisible, it can be confusing: e.g. a backslash
followed by a space and a newline does not count as
a line continuation marker. Some editors don’t
preserve it and many projects (like CPython itself)
have pre-commit hooks that reject it.
Yes:
i·=·i·+·1
submitted·+=·1
x·=·x*2·-·1
hypot2·=·x*x·+·y*y
c·=·(a+b)·*·(a-b)
No:
i=i+1
submitted·+=1
x·=·x·*·2·-·1
hypot2·=·x·*·x·+·y·*·y
c·=·(a·+·b)·*·(a·-·b)
Yes:
def·complex(real,·imag=0.0):
····return·magic(r=real,·i=imag)
No:
def·complex(real,·imag·=·0.0):
····return·magic(r·=·real,·i·=·imag)
Yes:
def·munge(input:·AnyStr):·...
def·munge()·->·AnyStr:·...
No:
def·munge(input:AnyStr):·...
def·munge()->PosInt:·...
Yes:
def·munge(sep:·AnyStr·=·None):·...
def·munge(input:·AnyStr,·sep:·AnyStr·=·Non
No:
def·munge(input:·AnyStr=None):·...
def·munge(input:·AnyStr,·limit·=·1000):·.
Compound statements (multiple statements on the
same line) are generally discouraged.
Yes:
if·foo·==·'blah':
····do_blah_thing()
do_one()
do_two()
do_three()
Rather not:
if·foo·==·'blah':·do_blah_thing()
do_one();·do_two();·do_three()
Rather not:
if·foo·==·'blah':·do_blah_thing()
for·x·in·lst:·total·+=·x
while·t·<·10:·t·=·delay()
Definitely not:
if·foo·==·'blah':·do_blah_thing()
else:·do_non_blah_thing()
try:·something()
finally:·cleanup()
do_one();·do_two();·do_three(long,·argumen
·····························list,·like,·t
if·foo·==·'blah':·one();·two();·three()
When to use
trailing commas
Trailing commas are usually optional, except they are
mandatory when making a tuple of one element (and in
Python 2 they have semantics for the print statement).
For clarity, it is recommended to surround the latter in
(technically redundant) parentheses.
Yes:
FILES·=·('setup.cfg',)
FILES·=·'setup.cfg',
FILES·=·[
····'setup.cfg',
····'tox.ini',
····]
initialize(FILES,
···········error=True,
···········)
No:
FILES·=·['setup.cfg',·'tox.ini',]
initialize(FILES,·error=True,)
Comments
Comments that contradict the code are worse than no
comments. Always make a priority of keeping the
comments up-to-date when the code changes!
Block Comments
Block comments generally apply to some (or all) code
that follows them, and are indented to the same level as
that code. Each line of a block comment starts with a #
and a single space (unless it is indented text inside the
comment).
Inline Comments
Use inline comments sparingly.
Don’t do this:
x·=·x·+·1·················# Increment x
But sometimes, this is useful:
Documentation Strings
Conventions for writing good documentation strings
(a.k.a. “docstrings”) are immortalized in PEP 257.
"""Return a foobang
Naming
Conventions
The naming conventions of Python’s library are a bit of a
mess, so we’ll never get this completely consistent –
nevertheless, here are the currently recommended
naming standards. New modules and packages (including
third party frameworks) should be written to these
standards, but where an existing library has a different
style, internal consistency is preferred.
Overriding Principle
Names that are visible to the user as public parts of the
API should follow conventions that reflect usage rather
than implementation.
Descriptive: Naming
Styles
There are a lot of different naming styles. It helps to be
able to recognize what naming style is being used,
independently from what they are used for.
The X11 library uses a leading X for all its public functions.
In Python, this style is generally deemed unnecessary
because attribute and method names are prefixed with an
object, and function names are prefixed with a module
name.
__double_leading_and_trailing_underscore__ :
“magic” objects or attributes that live in user-
controlled namespaces. E.g. __init__ , __import__
or __file__ . Never invent such names; only use
them as documented.
Prescriptive: Naming
Conventions
Names to Avoid
Never use the characters ‘l’ (lowercase letter el), ‘O’
(uppercase letter oh), or ‘I’ (uppercase letter eye) as
single character variable names.
ASCII Compatibility
Identifiers used in the standard library must be ASCII
compatible as described in the policy section of PEP 3131.
Package and Module
Names
Modules should have short, all-lowercase names.
Underscores can be used in the module name if it
improves readability. Python packages should also have
short, all-lowercase names, although the use of
underscores is discouraged.
Class Names
Class names should normally use the CapWords
convention.
from·typing·import·TypeVar
··VT_co·=·TypeVar('VT_co',·covariant=True)
··KT_contra·=·TypeVar('KT_contra',·contravaria
Exception Names
Because exceptions should be classes, the class naming
convention applies here. However, you should use the
suffix “Error” on your exception names (if the exception
actually is an error).
Function Names
Function names should be lowercase, with words
separated by underscores as necessary to improve
readability.
mixedCase is allowed only in contexts where that’s
already the prevailing style (e.g. threading.py), to retain
backwards compatibility.
Constants
Constants are usually defined on a module level and
written in all capital letters with underscores separating
words. Examples include MAX_OVERFLOW and TOTAL .
Designing for
inheritance
Always decide whether a class’s methods and instance
variables (collectively: “attributes”) should be public or
non-public. If in doubt, choose non-public; it’s easier to
make it public later than to make a public attribute non-
public.
Programming
Recommendations
Code should be written in a way that does not
disadvantage other implementations of Python
(PyPy, Jython, IronPython, Cython, Psyco, and such).
Yes:
if·foo·is·not·None:
No:
if·not·foo·is·None:
Yes:
def·f(x):·return·2*x
No:
f·=·lambda·x:·2*x
try:
····import·platform_specific_module
except·ImportError:
····platform_specific_module·=·None
try:
····process_data()
except·Exception·as·exc:
····raise·DataProcessingFailedError(str(ex
Yes:
try:
····value·=·collection[key]
except·KeyError:
····return·key_not_found(key)
else:
····return·handle_value(value)
No:
try:
····# Too broad!
····return·handle_value(collection[key])
except·KeyError:
····# Will also catch KeyError raised by h
····return·key_not_found(key)
Yes:
with·conn.begin_transaction():
····do_stuff_in_transaction(conn)
No:
with·conn:
····do_stuff_in_transaction(conn)
Yes:
def·foo(x):
····if·x·>=·0:
········return·math.sqrt(x)
····else:
········return·None
def·bar(x):
····if·x·<·0:
········return·None
····return·math.sqrt(x)
No:
def·foo(x):
····if·x·>=·0:
········return·math.sqrt(x)
def·bar(x):
····if·x·<·0:
········return
····return·math.sqrt(x)
Yes:
if·foo.startswith('bar'):
No:
if·foo[:3]·==·'bar':
Yes:
if·isinstance(obj,·int):
No:
if·type(obj)·is·type(1):
if·isinstance(obj,·basestring):
if·not·seq:
if·seq:
No:
if·len(seq):
if·not·len(seq):
Yes:
if·greeting:
No:
if·greeting·==·True:
Worse:
if·greeting·is·True:
Function Annotations
With the acceptance of PEP 484, the style rules for
function annotations are changing.
# type: ignore
Footnotes
1.
PEP 7, Style Guide for C Code, van Rossum↩
2.
Barry’s GNU Mailman style guide
http://barry.warsaw.us/software/STYLEGUIDE.txt↩
3.
Hanging indentation is a type-setting style where all
the lines in a paragraph are indented except the
first line. In the context of Python, the term is used
to describe a style where the opening parenthesis
of a parenthesized statement is the last non-
whitespace character of the line, with subsequent
lines being indented until the closing
parenthesis.↩
4.
Donald Knuth's The TeXBook, pages 195 and 196.↩
5.
http://www.wikipedia.com/wiki/CamelCase↩
6.
Typeshed repo https://github.com/python/typeshed↩
7.
Suggested syntax for Python 2.7 and straddling code
https://www.python.org/dev/peps/pep-
0484/#suggested-syntax-for-python-2-7-and-
straddling-code↩
Copyright
This document has been placed in the public domain.