PEP8 Cheatsheet
PEP8 Cheatsheet
Naming Conventions
Naming Styles
The best way to name your objects in Python is to use descriptive names to make it clear what the object represents.
Always try to use the most concise but descriptive names possible.
# Recommended
name = 'John Smith'
first_name, last_name = name.split()
print(last_name, first_name, sep=', ')
'Smith, John'
def multiply_by_two(x):
return x * 2
# Not recommended
x = 'John Smith'
y, z = x.split()
print(z, y, sep=', ')
'Smith, John'
def db(x):
return x * 2
Code Layout
Blank Lines
class MyFirstClass:
pass
class MySecondClass:
pass
def top_level_function():
return None
class MyClass:
def first_method(self):
return None
def second_method(self):
return None
Use blank lines sparingly inside functions to show clear steps. There is also a blank line before the return statement.
def calculate_variance(number_list):
sum_list = 0
for number in number_list:
sum_list = sum_list + number
mean = sum_list / len(number_list)
sum_squares = 0
for number in number_list:
sum_squares = sum_squares + number**2
mean_squares = sum_squares / len(number_list)
PEP 8 outlines ways to allow statements to run over several lines when limited to 79 characters long. Python will
assume line continuation if code is contained within parentheses, brackets, or braces:
If it is impossible to use implied continuation, then you can use backslashes to break lines instead:
If line breaking needs to occur around binary operators, like + and *, it should occur before the operator.
# Recommended
total = (first_variable
+ second_variable
- third_variable)
Indentation
Tabs vs. Spaces
The key indentation rules laid out by PEP 8 are the following:
To keep lines to under 79 characters, there is a style of indentation following a line break called hanging indent. This is
a typographical term meaning that every line, but the first in a paragraph or statement, is indented.
Note: When using a hanging indent, there must not be any arguments on the first line.
# Recommended
var = function(
arg_one, arg_two,
arg_three, arg_four)
# Not Recommended
var = function(arg_one, arg_two,
arg_three, arg_four)
Add extra indentation to distinguish the continued line from code contained inside the function.
# Recommended
def function(
arg_one, arg_two,
arg_three, arg_four):
return arg_one
# Not Recommended
def function(
arg_one, arg_two,
arg_three, arg_four):
return arg_one
PEP 8 provides the next way for the position of the closing brace in implied line continuations:
• Line up the closing brace with the first non-whitespace character of the previous line:
list_of_numbers = [
1, 2, 3,
4, 5, 6,
7, 8, 9
]
Comments
You should use comments to document code as it’s written. It is important to document your code so that you, and any
collaborators, can understand it. When you or someone else reads a comment, they should be able to easily understand
the code the comment applies to and how it fits in with the rest of your code.
Here are some key points to remember when adding comments to your code:
Block Comments
Use block comments to document a small section of code with the following rules provided for PEP 8:
• Indent block comments to the same level as the code they describe.
Inline Comments
Inline comments explain a single statement in a piece of code. They are useful to remind you, or explain to others, why
a certain line of code is necessary. Here’s what PEP 8 has to say about them:
• Write inline comments on the same line as the statement they refer to.
• Start inline comments with a # and a single space, like block comments.
Documentation strings, or docstrings, are strings enclosed in double ( """) or single (''') quotation marks that appear on
the first line of any function, class, method, or module. You can use them to explain and document a specific block of
code. There is an entire PEP, PEP 257, that covers docstrings.
• Surround docstrings with three double quotes on either side, as in """This is a docstring""".
• Write them for all public modules, functions, classes, and methods.
Surround the following binary operators with a single space on either side:
• Comparisons (==, !=, >, <. >=, <=) and (is, is not, in, not in).
Note: When = is used to assign a default value to a function argument, do not surround it with spaces.
# Recommended
def function(default_parameter=5):
# ...
Note: When there’s more than one operator in a statement, it is better to only add whitespace around the operators with
the lowest priority, especially when performing mathematical manipulation.
# Recommended
y = x**2 + 5
z = (x+y) * (x-y)
# Not Recommended
y = x ** 2 + 5
z = (x + y) * (x - y)
# Recommended
if x>5 and x%2==0:
print('x is larger than 5 and divisible by 2!')
# Not recommended
if x > 5 and x % 2 == 0:
print('x is larger than 5 and divisible by 2!')
Note: In slices, colons are operators with low priority. For this reason it is necessary to add whitespace arount it.
# Recommended
list[3:4]
# Recommended
my_list = [1, 2, 3]
# Not recommended
my_list = [ 1, 2, 3, ]
x = 5
y = 6
# Recommended
print(x, y)
# Not recommended
print(x , y)
• Before the open parenthesis that starts the argument list of a function call:
def double(x):
return x * 2
# Recommended
double(3)
# Not recommended
double (3)
# Recommended
list[3]
# Not recommended
list [3]
# Recommended
tuple = (1,)
# Not recommended
tuple = (1, )
# Recommended
var1 = 5
var2 = 6
some_long_var = 7
# Not recommended
var1 = 5
var2 = 6
some_long_var = 7
Note: The most important place to avoid adding whitespace is at the end of a line. This is known as
trailing whitespace.
Programming Recommendations
The following list outlines some cases to be considered by PEP8 to remove ambiguity and preserve consistency:
Don’t compare Boolean values to True or False using the equivalence operator.
# Recommended
my_bool = 6 > 5
if my_bool:
return '6 is bigger than 5'
# Not recommended
my_bool = 6 > 5
if my_bool == True:
return '6 is bigger than 5'
Use the fact that empty sequences are falsy in if statements. An empty list, string, or tuple, is equivalent to False.
# Recommended
my_list = []
if not my_list:
print('List is empty!')
# Not recommended
my_list = []
if not len(my_list):
print('List is empty!')
# Recommended
if x is not None:
return 'x exists!'
# Not recommended
if not x is None:
return 'x exists!'
Don’t use if x: when you mean if x is not None:. When a function with arguments that are None by default.
# Not Recommended
if arg:
# Do something with arg...
# Recommended
if arg is not None:
# Do something with arg...
# Recommended
if word.startswith('cat'):
print('The word starts with "cat"')
# Not recommended
if word[:3] == 'cat':
print('The word starts with "cat"')
# Recommended
if file_name.endswith('jpg'):
print('The file is a JPEG')
# Not recommended
if file_name[-3:] == 'jpg':
print('The file is a JPEG')