PEP 8 Style Guide For Python Code | Python.org

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 35

DownloadPEP 8 -- Style Guide For Python Code | Python.org
Open PDF In BrowserView PDF
PEP 8 -- Style Guide for Python Code | Python.org

Notice: While Javascript is not essential for this website, your interaction with the content will be limited. Please turn Javascript on for the full experience.
Python

PSF

Docs

PyPI

≡ Menu



Jobs

Search

Community

GO
GO

AA

Socialize

Smaller  Google+
Larger  Facebook
Reset

 Twitter
 Chat on IRC

Tweets by @ThePSF

The PSF

Python >>> Python Developer's Guide >>> PEP Index >>> PEP 8 -- Style Guide for Python Code

PEP 8 -- Style Guide for Python Code

The Python Software
Foundation is the organization

PEP:

8

behind Python. Become a

Title:

Style Guide for Python Code

member of the PSF and help

Author:

Guido van Rossum ,Barry Warsaw ,Nick Coghlan

advance the software and our
mission.


Status:

Active

Type:

Process

Created:

05-Jul-2001

Pos-

05-Jul-2001, 01-Aug-2013

Hisory:

Contents
Introduction
A Foolish Consisency is the Hobgoblin of Little Minds
Code Lay-out
Indentation
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Tabs or Spaces?
Maximum Line Length
Should a Line Break Before or After a Binary Operator?
Blank Lines
Source File Encoding
Imports
Module Level Dunder Names
String Quotes
Whitespace in Expressions and Statements
Pet Peeves
Other Recommendations
When to Use Trailing Commas
Comments
Block Comments
Inline Comments
Documentation Strings
Naming Conventions
Overriding Principle
Descriptive: Naming Styles
Prescriptive: Naming Conventions
Names to Avoid
ASCII Compatibility
Package and Module Names
Class Names
Type Variable Names
Exception Names
Global Variable Names
Function and Variable Names
Function and Method Arguments
Method Names and Insance Variables
Consants
Designing for Inheritance
Public and Internal Interfaces
Programming Recommendations
Function Annotations
Variable Annotations
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

References
Copyright

Introduction
This document gives coding conventions for the Python code comprisingthe sandard library in the main Python
disribution. Please see thecompanion informational PEP describing syle guidelines for the C codein the C
implementation of Python [1].
This document and PEP 257 (Docsring Conventions) were adapted fromGuido's original Python Style Guide
essay, with some additions fromBarry's syle guide [2].
This syle guide evolves over time as additional conventions areidentifed and pas conventions are rendered
obsolete by changes inthe language itself.
Many projects have their own coding syle guidelines. In the event of anyconficts, such project-specifc guides
take precedence for that project.

A Foolish Consisency is the Hobgoblin of Little Minds
One of Guido's key insights is that code is read much more often thanit is written. The guidelines provided here
are intended to improvethe readability of code and make it consisent across the widespectrum of Python code.
As PEP 20 says, "Readability counts".
A syle guide is about consisency. Consisency with this syle guideis important. Consisency within a project is
more important.Consisency within one module or function is the mos important.
However, know when to be inconsisent -- sometimes syle guiderecommendations jus aren't applicable. When
in doubt, use your besjudgment. Look at other examples and decide what looks bes. Anddon't hesitate to ask!
In particular: do not break backwards compatibility jus to comply withthis PEP!
Some other good reasons to ignore a particular guideline:
1. When applying the guideline would make the code less readable, evenfor someone who is used to reading

code that follows this PEP.
2. To be consisent with surrounding code that also breaks it (maybefor hisoric reasons) -- although this is also

an opportunity toclean up someone else's mess (in true XP syle).
3. Because the code in quesion predates the introduction of theguideline and there is no other reason to be

modifying that code.
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

4. When the code needs to remain compatible with older versions ofPython that don't support the feature

recommended by the syle guide.

Code Lay-out
Indentation
Use 4 spaces per indentation level.
Continuation lines should align wrapped elements either verticallyusing Python's implicit line joining inside
parentheses, brackets andbraces, or using a hanging indent [7]. When using a hangingindent the following
should be considered; there should be noarguments on the frs line and further indentation should be used to
clearly disinguish itself as a continuation line.
Yes:
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
# More indentation included to disinguish this from the res.
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
# Hanging indents should add a level.
foo = long_function_name(
var_one, var_two,
var_three, var_four)
No:
# Arguments on frs line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
var_three, var_four)
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

# Further indentation required as indentation is not disinguishable.
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
The 4-space rule is optional for continuation lines.
Optional:
# Hanging indents *may* be indented to other than 4 spaces.
foo = long_function_name(
var_one, var_two,
var_three, var_four)
When the conditional part of an if-satement is long enough to requirethat it be written across multiple lines, it's
worth noting that thecombination of a two character keyword (i.e. if), plus a single space,plus an opening
parenthesis creates a natural 4-space indent for thesubsequent lines of the multiline conditional. This can
produce a visualconfict with the indented suite of code nesed inside the if-satement,which would also
naturally be indented to 4 spaces. This PEP takes noexplicit position on how (or whether) to further visually
disinguish suchconditional lines from the nesed suite inside the if-satement.Acceptable options in this
situation include, but are not limited to:
# No extra indentation.
if (this_is_one_thing and
that_is_another_thing):
do_something()
# Add a comment, which will provide some disinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
do_something()
(Also see the discussion of whether to break before or after binaryoperators below.)
The closing brace/bracket/parenthesis on multiline consructs mayeither line up under the frs non-whitespace
character of the lasline of lis, as in:
my_lis = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
or it may be lined up under the frs character of the line thatsarts the multiline consruct, as in:
my_lis = [
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.
Tabs should be used solely to remain consisent with code that isalready indented with tabs.

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Python 3 disallows mixing the use of tabs and spaces for indentation.
Python 2 code indented with a mixture of tabs and spaces should beconverted to using spaces exclusively.
When invoking the Python 2 command line interpreter withthe -t option, it issues warnings about code that
illegally mixestabs and spaces. When using -tt these warnings become errors.These options are highly
recommended!

Maximum Line Length
Limit all lines to a maximum of 79 characters.
For fowing long blocks of text with fewer sructural resrictions(docsrings or comments), the line length should
be limited to 72characters.
Limiting the required editor window width makes it possible to haveseveral fles open side-by-side, and works
well when using codereview tools that present the two versions in adjacent columns.
The default wrapping in mos tools disrupts the visual sructure of thecode, making it more difcult to
undersand. The limits are chosen toavoid wrapping in editors with the window width set to 80, evenif the tool
places a marker glyph in the fnal column when wrappinglines. Some web based tools may not ofer dynamic
line wrapping at all.
Some teams srongly prefer a longer line length. For code maintainedexclusively or primarily by a team that can
reach agreement on thisissue, it is okay to increase the nominal line length from 80 to100 characters
(efectively increasing the maximum length to 99characters), provided that comments and docsrings are sill
wrappedat 72 characters.
The Python sandard library is conservative and requires limitinglines to 79 characters (and
docsrings/comments to 72).
The preferred way of wrapping long lines is by using Python's impliedline continuation inside parentheses,
brackets and braces. Long linescan be broken over multiple lines by wrapping expressions inparentheses.
These should be used in preference to using a backslashfor line continuation.
Backslashes may sill be appropriate at times. For example, long,multiple with-satements cannot use implicit
continuation, sobackslashes are acceptable:

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

with open('/path/to/some/fle/you/want/to/read') as fle_1, \
open('/path/to/some/fle/being/written', 'w') as fle_2:
fle_2.write(fle_1.read())
(See the previous discussion on multiline if-satements for furtherthoughts on the indentation of such multiline
with-satements.)

Another such case is with assert satements.
Make sure to indent the continued line appropriately.

Should a Line Break Before or After a Binary Operator?
For decades the recommended syle was to break after binary operators.But this can hurt readability in two
ways: the operators tend to getscattered across diferent columns on the screen, and each operator ismoved
away from its operand and onto the previous line. Here, the eyehas to do extra work to tell which items are
added and which aresubtracted:
# No: operators sit far away from their operands
income = (gross_wages +
taxable_interes +
(dividends - qualifed_dividends) ira_deduction sudent_loan_interes)
To solve this readability problem, mathematicians and their publishersfollow the opposite convention. Donald
Knuth explains the traditionalrule in his Computers and Typesetting series: "Although formulaswithin a
paragraph always break after binary operations and relations,displayed formulas always break before binary
operations" [3].
Following the tradition from mathematics usually results in morereadable code:
# Yes: easy to match operators with operands
income = (gross_wages
+ taxable_interes
+ (dividends - qualifed_dividends)
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

- ira_deduction
- sudent_loan_interes)
In Python code, it is permissible to break before or after a binaryoperator, as long as the convention is
consisent locally. For newcode Knuth's syle is suggesed.

Blank Lines
Surround top-level function and class defnitions with two blanklines.
Method defnitions inside a class are surrounded by a single blankline.
Extra blank lines may be used (sparingly) to separate groups ofrelated functions. Blank lines may be omitted
between a bunch ofrelated one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
Python accepts the control-L (i.e. ^L) form feed character aswhitespace; Many tools treat these characters as
page separators, soyou may use them to separate pages of related sections of your fle.Note, some editors and
web-based code viewers may not recognizecontrol-L as a form feed and will show another glyph in its place.

Source File Encoding
Code in the core Python disribution should always use UTF-8 (or ASCIIin Python 2).
Files using ASCII (in Python 2) or UTF-8 (in Python 3) should not havean encoding declaration.
In the sandard library, non-default encodings should be used only fortes purposes or when a comment or
docsring needs to mention an authorname that contains non-ASCII characters; otherwise, using \x, \u, \U, or
\N

escapes is the preferred way to includenon-ASCII data in sring literals.

For Python 3.0 and beyond, the following policy is prescribed for thesandard library (see PEP 3131): All
identifers in the Pythonsandard library MUST use ASCII-only identifers, and SHOULD useEnglish words
wherever feasible (in many cases, abbreviations andtechnical terms are used which aren't English). In
addition, sringliterals and comments mus also be in ASCII. The only exceptions are(a) tes cases tesing the
non-ASCII features, and(b) names of authors. Authors whose names are not based on theLatin alphabet (latin1, ISO/IEC 8859-1 character set) MUST providea transliteration of their names in this character set.

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Open source projects with a global audience are encouraged to adopt asimilar policy.

Imports
Imports should usually be on separate lines:
Yes: import os
import sys
No:

import sys, os

It's okay to say this though:
from subprocess import Popen, PIPE
Imports are always put at the top of the fle, jus after any modulecomments and docsrings, and before
module globals and consants.
Imports should be grouped in the following order:
1. Standard library imports.
2. Related third party imports.
3. Local application/library specifc imports.

You should put a blank line between each group of imports.
Absolute imports are recommended, as they are usually more readableand tend to be better behaved (or at
leas give better errormessages) if the import sysem is incorrectly confgured (such aswhen a directory
inside a package ends up on sys.path):
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example
However, explicit relative imports are an acceptable alternative toabsolute imports, especially when dealing
with complex package layoutswhere using absolute imports would be unnecessarily verbose:
from . import sibling
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

from .sibling import example
Standard library code should avoid complex package layouts and alwaysuse absolute imports.
Implicit relative imports should never be used and have been removedin Python 3.
When importing a class from a class-containing module, it's usuallyokay to spell this:
from myclass import MyClass
from foo.bar.yourclass import YourClass
If this spelling causes local name clashes, then spell them explicitly:
import myclass
import foo.bar.yourclass
and use "myclass.MyClass" and "foo.bar.yourclass.YourClass".
Wildcard imports (from  import *) should be avoided, asthey make it unclear which names are
present in the namespace,confusing both readers and many automated tools. There is onedefensible use
case for a wildcard import, which is to republish aninternal interface as part of a public API (for example,
overwritinga pure Python implementation of an interface with the defnitionsfrom an optional accelerator
module and exactly which defnitionswill be overwritten isn't known in advance).
When republishing names this way, the guidelines below regardingpublic and internal interfaces sill apply.

Module Level Dunder Names
Module level "dunders" (i.e. names with two leading and two trailingunderscores) such as __all__, __author__,
__version__,etc.
__future__

should be placed after the module docsring but before any importsatements except from

imports. Python mandates thatfuture-imports mus appear in the module before any other code

exceptdocsrings:
"""This is the example module.
This module does suf.
"""
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

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 srings and double-quoted srings are thesame. This PEP does not make a
recommendation for this. Pick a ruleand sick to it. When a sring contains single or double quotecharacters,
however, use the other one to avoid backslashes in thesring. It improves readability.
For triple-quoted srings, always use double quote characters to beconsisent with the docsring convention in
PEP 257.

Whitespace in Expressions and Statements
Pet Peeves
Avoid extraneous whitespace in the following situations:
Immediately inside parentheses, brackets or braces.
Yes: spam(ham[1], {eggs: 2})
No:

spam( ham[ 1 ], { eggs: 2 } )

Between a trailing comma and a following close parenthesis.
Yes: foo = (0,)
No:

bar = (0, )

Immediately before a comma, semicolon, or colon:

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Yes: if x == 4: print x, y; x, y = y, x
No:

if x == 4 : print x , y ; x , y = y , x

However, in a slice the colon acts like a binary operator, andshould have equal amounts on either side
(treating it as theoperator with the lowes priority). In an extended slice, bothcolons mus have the same
amount of spacing applied. Exception:when a slice parameter is omitted, the space is omitted.
Yes:
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::sep]
ham[lower+ofset : upper+ofset]
ham[: upper_fn(x) : sep_fn(x)], ham[:: sep_fn(x)]
ham[lower + ofset : upper + ofset]
No:
ham[lower + ofset:upper + ofset]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : upper]
ham[ : upper]
Immediately before the open parenthesis that sarts the argumentlis of a function call:
Yes: spam(1)
No:

spam (1)

Immediately before the open parenthesis that sarts an indexing orslicing:
Yes: dct['key'] = ls[index]
No:

dct ['key'] = ls [index]

More than one space around an assignment (or other) operator toalign it with another.
Yes:

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

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 anewline does not count as a line continuation marker. Some editorsdon't preserve
it and many projects (like CPython itself) havepre-commit hooks that reject it.
Always surround these binary operators with a single space on eitherside: assignment ( =), augmented
assignment (+=, -=etc.), comparisons ( ==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or,
not).

If operators with diferent priorities are used, consider addingwhitespace around the operators with the
lowes priority(ies). Useyour own judgment; however, never use more than one space, andalways have the
same amount of whitespace on both sides of a binaryoperator.
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
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
Don't use spaces around the = sign when used to indicate akeyword argument or a default parameter value.
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)
Function annotations should use the normal rules for colons andalways have spaces around the -> arrow if
present. (SeeFunction Annotations below for more about function annotations.)
Yes:
def munge(input: AnyStr): ...
def munge() -> AnyStr: ...
No:
def munge(input:AnyStr): ...
def munge()->PosInt: ...
When combining an argument annotation with a default value, usespaces around the = sign (but only for
those arguments that haveboth an annotation and a default).
Yes:
def munge(sep: AnyStr = None): ...
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ...
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

No:
def munge(input: AnyStr=None): ...
def munge(input: AnyStr, limit = 1000): ...
Compound satements (multiple satements on the same line) aregenerally 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()
While sometimes it's okay to put an if/for/while with a small bodyon the same line, never do this for multiclause satements. Alsoavoid folding such long lines!
Rather not:
if foo == 'blah': do_blah_thing()
for x in ls: total += x
while t < 10: t = delay()
Defnitely not:
if foo == 'blah': do_blah_thing()
else: do_non_blah_thing()
try: something()
fnally: cleanup()
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

do_one(); do_two(); do_three(long, argument,
lis, like, this)
if foo == 'blah': one(); two(); three()

When to Use Trailing Commas
Trailing commas are usually optional, except they are mandatory whenmaking a tuple of one element (and in
Python 2 they have semantics forthe print satement). For clarity, it is recommended to surroundthe latter in
(technically redundant) parentheses.
Yes:
FILES = ('setup.cfg',)
OK, but confusing:
FILES = 'setup.cfg',
When trailing commas are redundant, they are often helpful when aversion control sysem is used, when a lis
of values, arguments orimported items is expected to be extended over time. The pattern isto put each value
(etc.) on a line by itself, always adding a trailingcomma, and add the close parenthesis/bracket/brace on the
next line.However it does not make sense to have a trailing comma on the sameline as the closing delimiter
(except in the above case of singletontuples).
Yes:
FILES = [
'setup.cfg',
'tox.ini',
]
initialize(FILES,
error=True,
)

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

No:
FILES = ['setup.cfg', 'tox.ini',]
initialize(FILES, error=True,)

Comments
Comments that contradict the code are worse than no comments. Alwaysmake a priority of keeping the
comments up-to-date when the codechanges!
Comments should be complete sentences. The frs word should becapitalized, unless it is an identifer that
begins with a lower caseletter (never alter the case of identifers!).
Block comments generally consis of one or more paragraphs built out ofcomplete sentences, with each
sentence ending in a period.
You should use two spaces after a sentence-ending period in multi-sentence comments, except after the fnal
sentence.
When writing English, follow Strunk and White.
Python coders from non-English speaking countries: please write yourcomments in English, unless you are
120% sure that the code will neverbe read by people who don't speak your language.

Block Comments
Block comments generally apply to some (or all) code that followsthem, and are indented to the same level as
that code. Each line of ablock comment sarts with a # and a single space (unless it isindented text inside the
comment).
Paragraphs inside a block comment are separated by a line containing asingle #.

Inline Comments
Use inline comments sparingly.
An inline comment is a comment on the same line as a satement.Inline comments should be separated by at
leas two spaces from thesatement. They should sart with a # and a single space.

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Inline comments are unnecessary and in fact disracting if they satethe obvious. Don't do this:
x = x + 1

# Increment x

But sometimes, this is useful:
x = x + 1

# Compensate for border

Documentation Strings
Conventions for writing good documentation srings(a.k.a. "docsrings") are immortalized in PEP 257.
Write docsrings for all public modules, functions, classes, andmethods. Docsrings are not necessary for
non-public methods, butyou should have a comment that describes what the method does. Thiscomment
should appear after the def line.
PEP 257 describes good docsring conventions. Note that mosimportantly, the """ that ends a multiline
docsring should beon a line by itself:
"""Return a foobang
Optional plotz says to frobnicate the bizbaz frs.
"""
For one liner docsrings, please keep the closing """ onthe same line.

Naming Conventions
The naming conventions of Python's library are a bit of a mess, sowe'll never get this completely consisent -nevertheless, here arethe currently recommended naming sandards. New modules and packages(including
third party frameworks) should be written to thesesandards, but where an exising library has a diferent syle,
internal consisency is preferred.

Overriding Principle
Names that are visible to the user as public parts of the API shouldfollow conventions that refect usage rather
than implementation.
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Descriptive: Naming Styles
There are a lot of diferent naming syles. It helps to be able torecognize what naming syle is being used,
independently from whatthey are used for.
The following naming syles are commonly disinguished:
b

(single lowercase letter)

B

(single uppercase letter)

lowercase

lower_case_with_underscores

UPPERCASE

UPPER_CASE_WITH_UNDERSCORES

CapitalizedWords

(or CapWords, or CamelCase -- so named becauseof the bumpy look of its letters [4]).

This is also sometimes knownas StudlyCaps.
Note: When using acronyms in CapWords, capitalize all theletters of the acronym. Thus HTTPServerError is
better thanHttpServerError.
mixedCase

(difers from CapitalizedWords by initial lowercasecharacter!)

Capitalized_Words_With_Underscores

(ugly!)

There's also the syle of using a short unique prefx to group relatednames together. This is not used much in
Python, but it is mentionedfor completeness. For example, the os.sat() function returns atuple whose items
traditionally have names like s_mode, s_size, s_mtime and so on. (This is done to emphasize the
correspondence with the felds of the POSIX sysem call sruct, whichhelps programmers familiar with that.)
The X11 library uses a leading X for all its public functions. InPython, this syle is generally deemed
unnecessary because attributeand method names are prefxed with an object, and function names areprefxed
with a module name.
In addition, the following special forms using leading or trailingunderscores are recognized (these can generally
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

be combined with anycase convention):
_single_leading_underscore:

weak "internal use" indicator.E.g. from M import * does not import objects

whose name sartswith an underscore.
single_trailing_underscore_:

used by convention to avoidconficts with Python keyword, e.g.

Tkinter.Toplevel(maser, class_='ClassName')
__double_leading_underscore:
__boo

when naming a class attribute,invokes name mangling (inside class FooBar,

becomes _FooBar__boo; see below).

__double_leading_and_trailing_underscore__:

"magic" objects orattributes that live in user-controlled

namespaces.E.g. __init__, __import__ or __fle__. Never inventsuch names; only use them as documented.

Prescriptive: Naming Conventions
Names to Avoid
Never use the characters 'l' (lowercase letter el), 'O' (uppercaseletter oh), or 'I' (uppercase letter eye) as single
character variablenames.
In some fonts, these characters are indisinguishable from thenumerals one and zero. When tempted to use 'l',
use 'L' insead.

ASCII Compatibility
Identifers used in the sandard library mus be ASCII compatibleas described in the policy sectionof PEP 3131.

Package and Module Names
Modules should have short, all-lowercase names. Underscores can beused in the module name if it improves
readability. Python packagesshould also have short, all-lowercase names, although the use ofunderscores is
discouraged.
When an extension module written in C or C++ has an accompanyingPython module that provides a higher
level (e.g. more object oriented)interface, the C/C++ module has a leading underscore(e.g. _socket).
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Class Names
Class names should normally use the CapWords convention.
The naming convention for functions may be used insead in cases wherethe interface is documented and used
primarily as a callable.
Note that there is a separate convention for builtin names: mos builtinnames are single words (or two words
run together), with the CapWordsconvention used only for exception names and builtin consants.

Type Variable Names
Names of type variables introduced in PEP 484 should normally use CapWordspreferring short names: T,
AnyStr, Num.

It is recommended to addsufxes _co or _contra to the variables used to declare covariantor

contravariant behavior correspondingly:
from typing import TypeVar
VT_co = TypeVar('VT_co', covariant=True)
KT_contra = TypeVar('KT_contra', contravariant=True)

Exception Names
Because exceptions should be classes, the class naming conventionapplies here. However, you should use the
sufx "Error" on yourexception names (if the exception actually is an error).

Global Variable Names
(Let's hope that these variables are meant for use inside one moduleonly.) The conventions are about the same
as those for functions.
Modules that are designed for use via from M import * should usethe __all__ mechanism to prevent exporting
globals, or use theolder convention of prefxing such globals with an underscore (whichyou might want to do to
indicate these globals are "modulenon-public").

Function and Variable Names
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Function names should be lowercase, with words separated byunderscores as necessary to improve
readability.
Variable names follow the same convention as function names.
mixedCase is allowed only in contexts where that's already theprevailing syle (e.g. threading.py), to retain
backwardscompatibility.

Function and Method Arguments
Always use self for the frs argument to insance methods.
Always use cls for the frs argument to class methods.
If a function argument's name clashes with a reserved keyword, it isgenerally better to append a single trailing
underscore rather thanuse an abbreviation or spelling corruption. Thus class_ is betterthan clss. (Perhaps
better is to avoid such clashes by using asynonym.)

Method Names and Insance Variables
Use the function naming rules: lowercase with words separated byunderscores as necessary to improve
readability.
Use one leading underscore only for non-public methods and insancevariables.
To avoid name clashes with subclasses, use two leading underscores toinvoke Python's name mangling rules.
Python mangles these names with the class name: if class Foo has anattribute named __a, it cannot be
accessed by Foo.__a. (Aninsisent user could sill gain access by calling Foo._Foo__a.)Generally, double leading
underscores should be used only to avoidname conficts with attributes in classes designed to be subclassed.
Note: there is some controversy about the use of __names (see below).

Consants
Consants are usually defned on a module level and written in allcapital letters with underscores separating
words. Examples includeMAX_OVERFLOW and TOTAL.

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Designing for Inheritance
Always decide whether a class's methods and insance variables(collectively: "attributes") should be public or
non-public. If indoubt, choose non-public; it's easier to make it public later than tomake a public attribute nonpublic.
Public attributes are those that you expect unrelated clients of yourclass to use, with your commitment to avoid
backwards incompatiblechanges. Non-public attributes are those that are not intended to beused by third
parties; you make no guarantees that non-publicattributes won't change or even be removed.
We don't use the term "private" here, since no attribute is reallyprivate in Python (without a generally
unnecessary amount of work).
Another category of attributes are those that are part of the"subclass API" (often called "protected" in other
languages). Someclasses are designed to be inherited from, either to extend or modifyaspects of the class's
behavior. When designing such a class, takecare to make explicit decisions about which attributes are public,
which are part of the subclass API, and which are truly only to beused by your base class.
With this in mind, here are the Pythonic guidelines:
Public attributes should have no leading underscores.
If your public attribute name collides with a reserved keyword,append a single trailing underscore to your
attribute name. This ispreferable to an abbreviation or corrupted spelling. (However,notwithsanding this
rule, 'cls' is the preferred spelling for anyvariable or argument which is known to be a class, especially the
frs argument to a class method.)
Note 1: See the argument name recommendation above for class methods.
For simple public data attributes, it is bes to expose jus theattribute name, without complicated
accessor/mutator methods. Keepin mind that Python provides an easy path to future enhancement,should
you fnd that a simple data attribute needs to growfunctional behavior. In that case, use properties to hide
functional implementation behind simple data attribute accesssyntax.
Note 1: Properties only work on new-syle classes.
Note 2: Try to keep the functional behavior side-efect free,although side-efects such as caching are
generally fne.
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Note 3: Avoid using properties for computationally expensiveoperations; the attribute notation makes the
caller believe thataccess is (relatively) cheap.
If your class is intended to be subclassed, and you have attributesthat you do not want subclasses to use,
consider naming them withdouble leading underscores and no trailing underscores. Thisinvokes Python's
name mangling algorithm, where the name of theclass is mangled into the attribute name. This helps avoid
attribute name collisions should subclasses inadvertently containattributes with the same name.
Note 1: Note that only the simple class name is used in the mangledname, so if a subclass chooses both the
same class name and attributename, you can sill get name collisions.
Note 2: Name mangling can make certain uses, such as debugging and __getattr__(), less convenient.
However the name manglingalgorithm is well documented and easy to perform manually.
Note 3: Not everyone likes name mangling. Try to balance theneed to avoid accidental name clashes with
potential use byadvanced callers.

Public and Internal Interfaces
Any backwards compatibility guarantees apply only to public interfaces.Accordingly, it is important that users be
able to clearly disinguishbetween public and internal interfaces.
Documented interfaces are considered public, unless the documentationexplicitly declares them to be
provisional or internal interfaces exemptfrom the usual backwards compatibility guarantees. All undocumented
interfaces should be assumed to be internal.
To better support introspection, modules should explicitly declare thenames in their public API using the
__all__

attribute. Setting __all__ to an empty lis indicates that the module has no public API.

Even with __all__ set appropriately, internal interfaces (packages,modules, classes, functions, attributes or
other names) should sill beprefxed with a single leading underscore.
An interface is also considered internal if any containing namespace(package, module or class) is considered
internal.
Imported names should always be considered an implementation detail.Other modules mus not rely on indirect
access to such imported namesunless they are an explicitly documented part of the containing module'sAPI,
such as os.path or a package's __init__ module that exposesfunctionality from submodules.
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Programming Recommendations
Code should be written in a way that does not disadvantage otherimplementations of Python (PyPy, Jython,
IronPython, Cython, Psyco,and such).
For example, do not rely on CPython's efcient implementation ofin-place sring concatenation for
satements in the form a += bor a = a + b. This optimization is fragile even in CPython (itonly works for
some types) and isn't present at all in implementationsthat don't use refcounting. In performance sensitive
parts of thelibrary, the ''.join() form should be used insead. This willensure that concatenation occurs in
linear time across variousimplementations.
Comparisons to singletons like None should always be done with is or is not, never the equality operators.
Also, beware of writing if x when you really mean if x is notNone -- e.g. when tesing whether a variable
or argument thatdefaults to None was set to some other value. The other value mighthave a type (such as a
container) that could be false in a booleancontext!
Use is not operator rather than not ... is. While bothexpressions are functionally identical, the former is
more readableand preferred.
Yes:
if foo is not None:
No:
if not foo is None:
When implementing ordering operations with rich comparisons, it isbes to implement all six operations
(__eq__, __ne__, __lt__, __le__, __gt__, __ge__) rather than relyingon other code to only exercise a
particular comparison.
To minimize the efort involved, the functools.total_ordering()decorator provides a tool to generate
missing comparison methods.
PEP 207 indicates that refexivity rules are assumed by Python.Thus, the interpreter may swap y > x with x
< y, y >= xwith x <= y,

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

and may swap the arguments of x == y and x !=y . The sort() and min()

PEP 8 -- Style Guide for Python Code | Python.org

operations are guaranteed to usethe < operator and the max() function uses the >operator. However, it is
bes to implement all six operations sothat confusion doesn't arise in other contexts.
Always use a def satement insead of an assignment satement that bindsa lambda expression directly to
an identifer.
Yes:
def f(x): return 2*x
No:
f = lambda x: 2*x
The frs form means that the name of the resulting function object isspecifcally 'f' insead of the generic
''. This is moreuseful for tracebacks and sring representations in general. The useof the
assignment satement eliminates the sole beneft a lambdaexpression can ofer over an explicit def
satement (i.e. that it canbe embedded inside a larger expression)
Derive exceptions from Exception rather than BaseException.Direct inheritance from BaseException is
reserved for exceptionswhere catching them is almos always the wrong thing to do.
Design exception hierarchies based on the disinctions that code catching the exceptions is likely to need,
rather than the locationswhere the exceptions are raised. Aim to answer the quesion"What went wrong?"
programmatically, rather than only sating that"A problem occurred" (see PEP 3151 for an example of this
lesson beinglearned for the builtin exception hierarchy)
Class naming conventions apply here, although you should add thesufx "Error" to your exception classes if
the exception is anerror. Non-error exceptions that are used for non-local fow controlor other forms of
signaling need no special sufx.
Use exception chaining appropriately. In Python 3, "raise X from Y"should be used to indicate explicit
replacement without losing theoriginal traceback.
When deliberately replacing an inner exception (using "raise X" inPython 2 or "raise X from None" in Python
3.3+), ensure that relevantdetails are transferred to the new exception (such as preserving theattribute name
when converting KeyError to AttributeError, orembedding the text of the original exception in the new
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

exceptionmessage).
When raising an exception in Python 2, use raise ValueError('message')insead of the older form raise
ValueError, 'message'.

The latter form is not legal Python 3 syntax.
The paren-using form also means that when the exception arguments arelong or include sring formatting,
you don't need to use linecontinuation characters thanks to the containing parentheses.
When catching exceptions, mention specifc exceptions wheneverpossible insead of using a bare except:
clause:
try:
import platform_specifc_module
except ImportError:
platform_specifc_module = None
A bare except: clause will catch SysemExit andKeyboardInterrupt exceptions, making it harder to interrupt a
program with Control-C, and can disguise other problems. If youwant to catch all exceptions that signal
program errors, useexcept Exception: (bare except is equivalent to exceptBaseException: ).
A good rule of thumb is to limit use of bare 'except' clauses to twocases:
1. If the exception handler will be printing out or logging thetraceback; at leas the user will be aware that an

error hasoccurred.
2. If the code needs to do some cleanup work, but then lets theexception propagate upwards with raise.
try...fnallycan

be a better way to handle this case.

When binding caught exceptions to a name, prefer the explicit namebinding syntax added in Python 2.6:
try:
process_data()
except Exception as exc:
raise DataProcessingFailedError(sr(exc))
This is the only syntax supported in Python 3, and avoids theambiguity problems associated with the older
comma-based syntax.
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

When catching operating sysem errors, prefer the explicit exceptionhierarchy introduced in Python 3.3 over
introspection of errnovalues.
Additionally, for all try/except clauses, limit the try clauseto the absolute minimum amount of code
necessary. Again, thisavoids masking bugs.
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 handle_value()
return key_not_found(key)
When a resource is local to a particular section of code, use a with satement to ensure it is cleaned up
promptly and reliablyafter use. A try/fnally satement is also acceptable.
Context managers should be invoked through separate functions or methodswhenever they do something
other than acquire and release resources.
Yes:
with conn.begin_transaction():
do_suf_in_transaction(conn)
No:
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

with conn:
do_suf_in_transaction(conn)
The latter example doesn't provide any information to indicate thatthe __enter__ and __exit__ methods are
doing something otherthan closing the connection after a transaction. Being explicit isimportant in this case.
Be consisent in return satements. Either all return satements ina function should return an expression, or
none of them should. Ifany return satement returns an expression, any return satementswhere no value is
returned should explicitly sate this as returnNone , and an explicit return satement should be present at the
end of the function (if reachable).
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)

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Use sring methods insead of the sring module.
String methods are always much faser and share the same API withunicode srings. Override this rule if
backwards compatibility withPythons older than 2.0 is required.
Use ''.sartswith() and ''.endswith() insead of sringslicing to check for prefxes or sufxes.
sartswith() and endswith() are cleaner and less error prone:
Yes: if foo.sartswith('bar'):
No:

if foo[:3] == 'bar':

Object type comparisons should always use isinsance() insead ofcomparing types directly.
Yes: if isinsance(obj, int):
No:

if type(obj) is type(1):

When checking if an object is a sring, keep in mind that it mightbe a unicode sring too! In Python 2, sr and
unicode have acommon base class, basesring, so you can do:
if isinsance(obj, basesring):
Note that in Python 3, unicode and basesring no longer exis(there is only sr) and a bytes object is no longer
a kind ofsring (it is a sequence of integers insead).
For sequences, (srings, liss, tuples), use the fact that emptysequences are false.
Yes: if not seq:
if seq:
No:

if len(seq):
if not len(seq):

Don't write sring literals that rely on signifcant trailingwhitespace. Such trailing whitespace is visually
indisinguishableand some editors (or more recently, reindent.py) will trim them.

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Don't compare boolean values to True or False using ==.
Yes:

if greeting:

No:

if greeting == True:

Worse: if greeting is True:

Function Annotations
With the acceptance of PEP 484, the syle rules for functionannotations are changing.
In order to be forward compatible, function annotations in Python 3code should preferably use PEP 484
syntax. (There are someformatting recommendations for annotations in the previous section.)
The experimentation with annotation syles that was recommendedpreviously in this PEP is no longer
encouraged.
However, outside the sdlib, experiments within the rules of PEP 484are now encouraged. For example,
marking up a large third partylibrary or application with PEP 484 syle type annotations,reviewing how easy it
was to add those annotations, and observingwhether their presence increases code undersandability.
The Python sandard library should be conservative in adopting suchannotations, but their use is allowed for
new code and for bigrefactorings.
For code that wants to make a diferent use of function annotationsit is recommended to put a comment of
the form:
# type: ignore
near the top of the fle; this tells type checker to ignore allannotations. (More fne-grained ways of disabling
complaints fromtype checkers can be found in PEP 484.)
Like linters, type checkers are optional, separate tools. Pythoninterpreters by default should not issue any
messages due to typechecking and should not alter their behavior based on annotations.
Users who don't want to use type checkers are free to ignore them.However, it is expected that users of
third party library packagesmay want to run type checkers over those packages. For this purposePEP 484
recommends the use of sub fles: .pyi fles that are readby the type checker in preference of the
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

corresponding .py fles.Stub fles can be disributed with a library, or separately (withthe library author's
permission) through the typeshed repo [5].
For code that needs to be backwards compatible, type annotationscan be added in the form of comments.
See the relevant section ofPEP 484 [6].

Variable Annotations
PEP 526 introduced variable annotations. The syle recommendations for them aresimilar to those on function
annotations described above:
Annotations for module level variables, class and insance variables,and local variables should have a single
space after the colon.
There should be no space before the colon.
If an assignment has a right hand side, then the equality sign should haveexactly one space on both sides.
Yes:
code: int
class Point:
coords: Tuple[int, int]
label: sr = ''
No:
code:int
code : int

# No space after colon
# Space before colon

class Tes:
result: int=0

# No spaces around equality sign

Although the PEP 526 is accepted for Python 3.6, the variable annotationsyntax is the preferred syntax for
sub fles on all versions of Python(see PEP 484 for details).

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Footnotes
[7]

Hanging indentation is a type-setting syle where allthe lines in a paragraph are indented except the
frs line. Inthe context of Python, the term is used to describe a syle wherethe opening parenthesis
of a parenthesized satement is the lasnon-whitespace character of the line, with subsequent lines
beingindented until the closing parenthesis.

References
[1]

PEP 7, Style Guide for C Code, van Rossum

[2]

Barry's GNU Mailman syle guide http://barry.warsaw.us/software/STYLEGUIDE.txt

[3]

Donald Knuth's The TeXBook, pages 195 and 196.

[4]

http://www.wikipedia.com/wiki/CamelCase

[5]

Typeshed repo https://github.com/python/typeshed

[6]

Suggesed syntax for Python 2.7 and sraddling code https://www.python.org/dev/peps/pep0484/#suggesed-syntax-for-python-2-7-and-sraddling-code

Copyright
This document has been placed in the public domain.
Source: https://github.com/python/peps/blob/maser/pep-0008.txt

About

Downloads

Documentation

Community

Success Stories

News

Applications

All releases

Docs

Diversity

Arts

Python News

Quotes

Source code

Audio/Visual Talks

Mailing Liss

Business

Community News

Getting Started

Windows

Beginner's Guide

IRC

Education

PSF News

Help

Mac OS X

Developer's Guide

Forums

Engineering

PyCon News

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]

PEP 8 -- Style Guide for Python Code | Python.org

Python Brochure

Contributing
Developer's Guide
Issue Tracker

Other Platforms

FAQ

Python Conferences

Government

License

Non-English Docs

Special Interes Groups

Scientifc

Alternative
Implementations

PEP Index

Python Wiki

Software Development

Python Books

Python Logo

Python Essays

Merchandise

Python Events Archive
User Group Events
Archive

Code of Conduct

Core Mentorship

Python Events
User Group Events

Community Awards

python-dev lis

Events

Submit an Event

Help & General Contact

Diversity Initiatives

Submit Website Bug

Status

Copyright ©2001-2018. Python Software Foundation Legal Statements Privacy Policy Powered by Rackspace

https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]



Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.6
Linearized                      : No
Create Date                     : 2018:07:11 21:50:53+08:00
Creator                         : Internet Explorer 9.0000
Modify Date                     : 2018:07:11 21:51:10+08:00
Has XFA                         : No
XMP Toolkit                     : Adobe XMP Core 5.6-c015 81.157285, 2014/12/12-00:43:15
Metadata Date                   : 2018:07:11 21:51:10+08:00
Creator Tool                    : Internet Explorer 9.0000
Format                          : application/pdf
Title                           : PEP 8 -- Style Guide for Python Code | Python.org
Document ID                     : uuid:d5690e6f-a31b-4a30-8aec-cbd123ccde0f
Instance ID                     : uuid:7ba93931-bb10-46de-b2f1-6ecbaca52eb5
Producer                        : Acrobat Web Capture 15.0
Page Count                      : 35
EXIF Metadata provided by EXIF.tools

Navigation menu