0% found this document useful (0 votes)
565 views8 pages

PEP8 Cheatsheet

The document provides guidelines for writing clean and readable Python code based on PEP 8 (Python Enhancement Proposal 8), which is the official Python style guide. It covers naming conventions, code layout including blank lines and indentation, line length and breaking, comments, and whitespace in expressions and statements. The key guidelines include using lowercase names with underscores for functions and variables, surrounding top-level functions with two blank lines, indenting comments to the code level, and adding a single space around operators and before/after commas but not inside parentheses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
565 views8 pages

PEP8 Cheatsheet

The document provides guidelines for writing clean and readable Python code based on PEP 8 (Python Enhancement Proposal 8), which is the official Python style guide. It covers naming conventions, code layout including blank lines and indentation, line length and breaking, comments, and whitespace in expressions and statements. The key guidelines include using lowercase names with underscores for functions and variables, surrounding top-level functions with two blank lines, indenting comments to the code level, and adding a single space around operators and before/after commas but not inside parentheses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

PEP 8 — THE STYLE GUIDE FOR PYTHON CODE

Naming Conventions
Naming Styles

Type Naming Convention Examples


Function Use a lowercase word or words. Separate words by underscores to improve readability. function, my_function
Use a lowercase single letter, word, or words. Separate words with underscores to improve
Variable readability. x, var, my_variable
Start each word with a capital letter. Do not separate words with underscores. This style is
Class called camel case or pascal case. Model, MyClass
Method Use a lowercase word or words. Separate words with underscores to improve readability. class_method, method
Use an uppercase single letter, word, or words. Separate words with underscores to improve CONSTANT, MY_CONSTANT,
Constant readability. MY_LONG_CONSTANT
Use a short, lowercase word or words. Separate words with underscores to improve
Module readability. module.py, my_module.py
Package Use a short, lowercase word or words. Do not separate words with underscores. package, mypackage

How to Choose Names

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

Surround top-level functions and classes with two blank lines.

class MyFirstClass:
pass

class MySecondClass:
pass

def top_level_function():
return None

Surround method definitions inside classes with a single blank line.

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)

return mean_squares – mean**2

Maximum Line Length and Line Breaking

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:

def function(arg_one, arg_two,


arg_three, arg_four):
return arg_one

If it is impossible to use implied continuation, then you can use backslashes to break lines instead:

from mypkg import example1, \


example2, example3

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:

• Use 4 consecutive spaces to indicate indentation.

• Prefer spaces over tabs.

Indentation Following Line Breaks

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

Where to Put the Closing Brace

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:

• Limit the line length of comments and docstrings to 72 characters.

• Use complete sentences, starting with a capital letter.

• Make sure to update comments if you change 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.

• Start each line with a # followed by a single space.

• Separate paragraphs by a line containing a single #.

def quadratic(a, b, c, x):


# Calculate the solution to a quadratic equation using the quadratic
# formula.
#
# There are always two solutions to a quadratic equation, x_1 and x_2.
x_1 = (- b+(b**2-4*a*c)**(1/2)) / (2*a)
x_2 = (- b-(b**2-4*a*c)**(1/2)) / (2*a)
return x_1, x_2

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:

• Use inline comments sparingly.

• Write inline comments on the same line as the statement they refer to.

• Separate inline comments by two or more spaces from the statement.

• Start inline comments with a # and a single space, like block comments.

• Don’t use them to explain the obvious.

Below is an example of an inline comment:

x = 5 # This is an inline comment


Documentation Strings

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.

The most important rules applying to docstrings are the following:

• 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.

• Put the """ that ends a multiline docstring on a line by itself.

• For one-line docstrings, keep the """ on the same line.

def quadratic(a, b, c, x):


"""Solve quadratic equation via the quadratic formula.

A quadratic equation has the following form:


ax**2 + bx + c = 0

There always two solutions to a quadratic equation: x_1 & x_2.


"""
x_1 = (- b+(b**2-4*a*c)**(1/2)) / (2*a)
x_2 = (- b-(b**2-4*a*c)**(1/2)) / (2*a)

return x_1, x_2


Whitespace in Expressions and Statements
Whitespace Around Binary Operators

Surround the following binary operators with a single space on either side:

• Assignment operators (=, +=, -=, and so forth).

• Comparisons (==, !=, >, <. >=, <=) and (is, is not, in, not in).

• Booleans (and, not, or).

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]

# Treat the colon as the operator with lowest priority


list[x+1 : x+2]

# In an extended slice, both colons must be


# surrounded by the same amount of whitespace
list[3:4:5]
list[x+1 : x+2 : x+3]

# The space is omitted if a slice parameter is omitted


list[x+1 : x+2 :]
When to Avoid Adding Whitespace

• Immediately inside parentheses, brackets, or braces:

# Recommended
my_list = [1, 2, 3]

# Not recommended
my_list = [ 1, 2, 3, ]

• Before a comma, semicolon, or colon:

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)

• Before the open bracket that starts an index or slice:

# Recommended
list[3]

# Not recommended
list [3]

• Between a trailing comma and a closing parenthesis:

# Recommended
tuple = (1,)

# Not recommended
tuple = (1, )

• To align assignment operators:

# 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!')

Use is not rather than not ... is in if statements.

# 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...

Use .startswith() and .endswith() instead of slicing.

# 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')

You might also like