PEP 8 Style Guide For Python Code | Python.org
User Manual:
Open the PDF directly: View PDF .
Page Count: 35
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Menu
GO
Python >>> Python Developer's Guide >>> PEP Index >>> PEP 8 -- Style Guide for Python Code
PEP 8 -- Style Guide for Python Code
PEP: 8
Title: Style Guide for Python Code
Author:
<ncoghlan at gmail.com>
Status: Active
Type: Process
Created: 05-Jul-2001
Pos-
Hisory:
05-Jul-2001, 01-Aug-2013
Contents
Introduction
Code Lay-out
Indentation
Tweets by @ThePSF
The PSF
The Python Software
Foundation is the organization
behind Python. Become a
member of the PSF and help
advance the software and our
mission.
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 Jobs Community
A A Socialize
Smaller
Larger
Reset
Google+
Facebook
Twitter
Chat on IRC
Search
GO
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
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
Designing for Inheritance
Public and Internal Interfaces
Programming Recommendations
Function Annotations
Variable Annotations
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
References
Copyright
Introduction
implementation of Python [1].
This document and PEP 257
[2].
take precedence for that project.
The guidelines provided here
As PEP 20 says, "Readability counts".
When
Some other good reasons to ignore a particular guideline:
1.
code that follows this PEP.
2.
3.
modifying that code.
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
4.
Code Lay-out
Indentation
Use 4 spaces per indentation level.
hanging indent [7].
Yes:
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
foo = long_function_name(
var_one, var_two,
var_three, var_four)
No:
foo = long_function_name(var_one, var_two,
var_three, var_four)
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
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:
foo = long_function_name(
var_one, var_two,
var_three, var_four)
When the conditional part of an if
if
This can
if
naturally be indented to 4 spaces.
if
situation include, but are not limited to:
# No extra indentation.
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
1, 2, 3,
]
'd', 'e', 'f',
)
1, 2, 3,
]
'd', 'e', 'f',
)
Tabs or Spaces?
Spaces are the preferred indentation method.
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Python 3 disallows mixing the use of tabs and spaces for indentation.
-t option, it issues warnings about code that
When using -tt
recommended!
Maximum Line Length
Limit all lines to a maximum of 79 characters.
line wrapping at all.
brackets and braces.
with
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
(See the previous discussion on
with
Another such case is with assert
Make sure to indent the continued line appropriately.
Should a Line Break Before or After a Binary Operator?
away from its operand and onto the previous line.
Donald
Computers and Typesetting
operations" [3].
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Blank Lines
Blank lines may be omitted
Use blank lines in functions, sparingly, to indicate logical sections.
Source File Encoding
\x
\u, \U, or
\N
PEP 3131): All
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Imports
Imports should usually be on separate lines:
It's okay to say this though:
Imports should be grouped in the following order:
1. Standard library imports.
2. Related third party imports.
3.
You should put a blank line between each group of imports.
inside a package ends up on sys.path):
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Implicit relative imports should never
If this spelling causes local name clashes, then spell them explicitly:
and use "myclass.MyClass" and "foo.bar.yourclass.YourClass".
Wildcard imports (from <module> import *
Module Level Dunder Names
__all__, __author__,
__version__ except from
__future__ imports.
"""
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
String Quotes
This PEP does not make a
recommendation for this.
PEP 257.
Whitespace in Expressions and Statements
Pet Peeves
Avoid extraneous whitespace in the following situations:
Immediately inside parentheses, brackets or braces.
Between a trailing comma and a following close parenthesis.
Immediately before a comma, semicolon, or colon:
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
amount of spacing applied.
Yes:
No:
Yes:
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
x = 1
No:
x = 1
Other Recommendations
Avoid trailing whitespace anywhere.
=), augmented
assignment (+=, -= ==, <, >, !=, <>, <=
>=, in, not in, is, is not), Booleans (and
or,
not).
Yes:
No:
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Don't use spaces around the =
Yes:
return magic(r=real, i=imag)
No:
return magic(r = real, i = imag)
-> arrow if
present.
Function Annotations below for more about function annotations.)
Yes:
No:
= sign (but only for
Yes:
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
No:
Yes:
do_one()
do_two()
do_three()
Rather not:
Rather not:
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
When to Use Trailing Commas
print
(technically redundant) parentheses.
Yes:
OK, but confusing:
Yes:
'tox.ini',
]
error=True,
)
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
No:
Comments
Comments that contradict the code are worse than no comments.
Comments should be complete sentences.
sentence ending in a period.
sentence.
When writing English, follow Strunk and White.
Block Comments
that code. #
comment).
#.
Inline Comments
Use inline comments sparingly.
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Don't do this:
But sometimes, this is useful:
Documentation Strings
PEP 257.
should appear after the def line.
PEP 257""" that ends a multiline
"""
"""
Naming Conventions
Overriding Principle
than implementation.
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Descriptive: Naming Styles
b (single lowercase letter)
B (single uppercase letter)
lowercase
lower_case_with_underscores
UPPERCASE
UPPER_CASE_WITH_UNDERSCORES
CapitalizedWords [4]).
Thus HTTPServerError is
mixedCase
Capitalized_Words_With_Underscores (ugly!)
This is not used much in
For example, the
traditionally have names like
, and so on. (This is done to emphasize the
The X11 library uses a leading X for all its public functions.
with a module name.
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
_single_leading_underscore from M import * does not import objects
single_trailing_underscore_
__double_leading_underscore
__boo
_FooBar__boo; see below).
__double_leading_and_trailing_underscore__
__init__, __import__ or .
Prescriptive: Naming Conventions
Names to Avoid
When tempted to use 'l',
ASCII Compatibility
policy section PEP 3131.
Package and Module Names
Modules should have short, all-lowercase names.
readability.
discouraged.
_socket).
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Class Names
Class names should normally use the CapWords convention.
primarily as a callable.
Type Variable Names
Names of type variables introduced in PEP 484 T,
AnyStr, Num _co or _contra
contravariant behavior correspondingly:
Exception Names
However, you should use the
Global Variable Names
The conventions are about the same
as those for functions.
Modules that are designed for use via from M import * __all__ mechanism to prevent exporting
Function and Variable Names
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
readability.
Variable names follow the same convention as function names.
Function and Method Arguments
Always use self
Always use cls
Thus class_ clss. (Perhaps
readability.
__a, it cannot be
accessed by Foo.__a. Foo._Foo__a
Note: there is some controversy about the use of __names (see below).
words.
MAX_OVERFLOW and TOTAL.
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Designing for Inheritance
non-public.
public.
unnecessary amount of work).
languages).
behavior.
With this in mind, here are the Pythonic guidelines:
Public attributes should have no leading underscores.
attribute name.
Note 1: See the argument name recommendation above for class methods.
accessor/mutator methods.
In that case, use properties to hide
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
This helps avoid
__getattr__(), less convenient.
Note 3: Not everyone likes name mangling.
Public and Internal Interfaces
__all__
__all__
Even with __all__
internal.
such as os.path or a package's __init__
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Programming Recommendations
a += b a = a + b.
In performance sensitive
''.join()
is or is not, never the equality operators.
Also, beware of writing if x when you really mean
Use is not operator rather than not ... is.
Yes:
No:
(__eq__, __ne__
__lt__, __le__, __gt__, __ge__
particular comparison.
functools.total_ordering()
missing comparison methods.
PEP 207are y > x with x
< y, y >= x x <= y, and may swap the arguments of x == y and . The sort() and min()
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
<
operator and the
max()
function uses the
>
However, it is
Yes:
No:
Derive exceptions from Exception rather than BaseException BaseException is
catching the exceptions is likely to need,
PEP 3151 for an example of this
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
When raising an exception in Python 2, use raise ValueError('message') raise
ValueError, 'message'.
The latter form is not legal Python 3 syntax.
except:
clause:
A bare except:
except Exception: (bare except is equivalent to ).
1.
2. raise.
comma-based syntax.
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
introspection of errno
Additionally, for all try/except clauses, limit the try
necessary.
Yes:
return handle_value(value)
No:
with
other than acquire and release resources.
Yes:
No:
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
with conn:
__enter__ and __exit__ methods are
none of them should.
Yes:
def foo(x):
return None
return None
No:
def foo(x):
return
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Override this rule if
Use and ''.endswith()
Note that in Python 3, unicode and ) and a bytes object is no longer
Such trailing whitespace is visually
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Don't compare boolean values to True or False using
==
.
No: if greeting == True:
Function Annotations
With the acceptance of PEP 484
PEP 484
syntax.
encouraged.
PEP 484For example,
PEP 484
the form:
PEP 484.)
Like linters, type checkers are optional, separate tools.
PEP 484
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
permission) through the typeshed repo [5].
PEP 484 [6].
Variable Annotations
PEP 526
annotations described above:
space after the colon.
There should be no space before the colon.
Yes:
code: int
No:
Although the PEP 526
PEP 484 for details).
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Footnotes
[7] Hanging indentation
References
[1] PEP 7, Style Guide for C Code, van Rossum
[2]
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]
https://github.com/python/typeshed
[6]
https://www.python.org/dev/peps/pep-
Copyright
This document has been placed in the public domain.
About
Applications
Quotes
Getting Started
Help
Downloads
All releases
Source code
Windows
Mac OS X
Documentation
Docs
Audio/Visual Talks
Beginner's Guide
Developer's Guide
Community
Diversity
IRC
Forums
Success Stories
Arts
Business
Education
Engineering
News
Python News
Community News
PSF News
PyCon News
PEP 8 -- Style Guide for Python Code | Python.org
https://www.python.org/dev/peps/pep-0008/[2018/7/11 21:51:08]
Help & General Contact Diversity Initiatives Submit Website Bug Status
Copyright ©2001-2018. Python Software Foundation Legal Statements Privacy Policy Powered by Rackspace
Python Brochure Other Platforms
License
Alternative
Implementations
FAQ
Non-English Docs
PEP Index
Python Books
Python Essays
Python Conferences
Python Wiki
Python Logo
Merchandise
Community Awards
Code of Conduct
Government
Software Development
Events
Python Events
User Group Events
Python Events Archive
User Group Events
Archive
Submit an Event
Contributing
Developer's Guide
Issue Tracker
Core Mentorship