How To Write Beautiful Python Code
How To Write Beautiful Python Code
With PEP 8
Table of Contents
Watch NowThis tutorial has a related video course created by the Real Python
team. Watch it together with the written tutorial to deepen your
understanding: Writing Beautiful Pythonic Code With PEP 8
PEP 8, sometimes spelled PEP8 or PEP-8, is a document that provides
guidelines and best practices on how to write Python code. It was written in
2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. The primary
focus of PEP 8 is to improve the readability and consistency of Python code.
PEP stands for Python Enhancement Proposal, and there are several of them. A
PEP is a document that describes new features proposed for Python and
documents aspects of Python, like design and style, for the community.
This tutorial outlines the key guidelines laid out in PEP 8. It’s aimed at
beginner to intermediate programmers, and as such I have not covered some
of the most advanced topics. You can learn about these by reading the
full PEP 8 documentation.
As Guido van Rossum said, “Code is read much more often than it is written.”
You may spend a few minutes, or a whole day, writing a piece of code to
process user authentication. Once you’ve written it, you’re never going to
write it again. But you’ll definitely have to read it again. That piece of code
might remain part of a project you’re working on. Every time you go back to
that file, you’ll have to remember what that code does and why you wrote it,
so readability matters.
If you’re new to Python, it can be difficult to remember what a piece of code
does a few days, or weeks, after you wrote it. If you follow PEP 8, you can be
sure that you’ve named your variables well. You’ll know that you’ve added
enough whitespace so it’s easier to follow logical steps in your code. You’ll
also have commented your code well. All this will mean your code is more
readable and easier to come back to. As a beginner, following the rules of PEP
8 can make learning Python a much more pleasant task.
If you have more experience writing Python code, then you may need to
collaborate with others. Writing readable code here is crucial. Other people,
who may have never met you or seen your coding style before, will have to
read and understand your code. Having guidelines that you follow and
recognize will make it easier for others to read your code.
Naming Conventions
“Explicit is better than implicit.”
Naming Styles
The table below outlines some of the common naming styles in Python code
and when you should use them:
Choosing names for your variables, functions, classes, and so forth can be
challenging. You should put a fair amount of thought into your naming
choices when writing code as it will make your code more readable. The best
way to name your objects in Python is to use descriptive names to make it
clear what the object represents.
>>>
>>> # Recommended
>>> name = 'John Smith'
>>> first_name, last_name = [Link]()
>>> print(last_name, first_name, sep=', ')
'Smith, John'
Similarly, to reduce the amount of typing you do, it can be tempting to use
abbreviations when choosing names. In the example below, I have defined a
function db() that takes a single argument x and doubles it:
# Not recommended
def db(x):
return x * 2
At first glance, this could seem like a sensible choice. db() could easily be an
abbreviation for double. But imagine coming back to this code in a few days.
You may have forgotten what you were trying to achieve with this function,
and that would make guessing how you abbreviated it difficult.
The following example is much clearer. If you come back to this code a couple
of days after writing it, you’ll still be able to read and understand the purpose
of this function:
# Recommended
def multiply_by_two(x):
return x * 2
The same philosophy applies to all other data types and objects in Python.
Always try to use the most concise but descriptive names possible.
Code Layout
“Beautiful is better than ugly.”
Blank Lines
Vertical whitespace, or blank lines, can greatly improve the readability of your
code. Code that’s bunched up together can be overwhelming and hard to
read. Similarly, too many blank lines in your code makes it look very sparse,
and the reader might need to scroll more than necessary. Below are three key
guidelines on how to use vertical whitespace.
Surround top-level functions and classes with two blank lines. Top-level
functions and classes should be fairly self-contained and handle separate
functionality. It makes sense to put extra vertical space around them, so that
it’s clear they are separate:
class MyFirstClass:
pass
class MySecondClass:
pass
def top_level_function():
return None
Surround method definitions inside classes with a single blank line. Inside
a class, functions are all related to one another. It’s good practice to leave only
a single line between them:
class MyClass:
def first_method(self):
return None
def second_method(self):
return None
Use blank lines sparingly inside functions to show clear steps. Sometimes,
a complicated function has to complete several steps before
the return statement. To help the reader understand the logic inside the
function, it can be helpful to leave a blank line between each step.
In the example below, there is a function to calculate the variance of a list. This
is two-step problem, so I have indicated each step by leaving a blank line
between them. There is also a blank line before the return statement. This
helps the reader clearly see what’s returned:
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)
If line breaking needs to occur around binary operators, like + and *, it should
occur before the operator. This rule stems from mathematics. Mathematicians
agree that breaking before binary operators improves readability. Compare
the following two examples.
# Recommended
total = (first_variable
+ second_variable
- third_variable)
You can immediately see which variable is being added or subtracted, as the
operator is right next to the variable being operated on.
Indentation
“There should be one—and preferably only one—obvious way to do it.”
x = 3
if x > 5:
print('x is larger than 5')
The indented print statement lets Python know that it should only be
executed if the if statement returns True. The same indentation applies to tell
Python what code to execute when a function is called or what code belongs
to a given class.
The key indentation rules laid out by PEP 8 are the following:
If you’re using Python 2 and have used a mixture of tabs and spaces to indent
your code, you won’t see errors when trying to run it. To help you to check
consistency, you can add a -t flag when running Python 2 code from the
command line. The interpreter will issue warnings when you are inconsistent
with your use of tabs and spaces:
$ python2 -t [Link]
[Link]: inconsistent use of tabs and spaces in indentation
If, instead, you use the -tt flag, the interpreter will issue errors instead of
warnings, and your code will not run. The benefit of using this method is that
the interpreter tells you where the inconsistencies are:
$ python3 [Link]
File "[Link]", line 3
print(i, j)
^
TabError: inconsistent use of tabs and spaces in indentation
You can write Python code with either tabs or spaces indicating indentation.
But, if you’re using Python 3, you must be consistent with your choice.
Otherwise, your code will not run. PEP 8 recommends that you always use 4
consecutive spaces to indicate indentation.
The first of these is to align the indented block with the opening delimiter:
x = 5
if (x > 3 and
x < 10):
print(x)
In this case, PEP 8 provides two alternatives to help improve readability:
var = function(
arg_one, arg_two,
arg_three, arg_four)
Note: When you’re using a hanging indent, there must not be any arguments
on the first line. The following example is not PEP 8 compliant:
# Not Recommended
var = function(arg_one, arg_two,
arg_three, arg_four)
When using a hanging indent, add extra indentation to distinguish the
continued line from code contained inside the function. The following
example is difficult to read because the code inside the function is at the same
indentation level as the continued lines:
# Not Recommended
def function(
arg_one, arg_two,
arg_three, arg_four):
return arg_one
Instead, it’s better to use a double indent on the line continuation. This helps
you to distinguish between function arguments and the function body,
improving readability:
def function(
arg_one, arg_two,
arg_three, arg_four):
return arg_one
When you write PEP 8 compliant code, the 79 character line limit forces you to
add line breaks in your code. To improve readability, you should indent a
continued line to show that it is a continued line. There are two ways of doing
this. The first is to align the indented block with the opening delimiter. The
second is to use a hanging indent. You are free to chose which method of
indentation you use following a line break.
Where to Put the Closing Brace
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
]
Line up the closing brace with the first character of the line that starts
the construct:
list_of_numbers = [
1, 2, 3,
4, 5, 6,
7, 8, 9
]
You are free to chose which option you use. But, as always, consistency is key,
so try to stick to one of the above methods.
Comments
“If the implementation is hard to explain, it’s a bad idea.”
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. They are useful
when you have to write several lines of code to perform a single action, such
as importing data from a file or updating a database entry. They are important
as they help others understand the purpose and functionality of a given code
block.
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 #.
Here is a block comment explaining the function of a for loop. Note that the
sentence wraps to a new line to preserve the 79 character line limit:
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:
x = 5
x = x * 5 # Multiply x by 5
Inline comments are more specific than block comments, and it’s easy to add
them when they’re not necessary, which leads to clutter. You could get away
with only using block comments so, unless you are sure you need an inline
comment, your code is more likely to be PEP 8 compliant if you stick to block
comments.
Documentation Strings
Surround the following binary operators with a single space on either side:
# Recommended
def function(default_parameter=5):
# ...
# Not recommended
def function(default_parameter = 5):
# ...
When there’s more than one operator in a statement, adding a single space
before and after each operator can look confusing. Instead, it is better to only
add whitespace around the operators with the lowest priority, especially when
performing mathematical manipulation. Here are a couple examples:
# Recommended
y = x**2 + 5
z = (x+y) * (x-y)
# Not Recommended
y = x ** 2 + 5
z = (x + y) * (x - y)
You can also apply this to if statements where there are multiple conditions:
# Not recommended
if x > 5 and x % 2 == 0:
print('x is larger than 5 and divisible by 2!')
In the above example, the and operator has lowest priority. It may therefore be
clearer to express the if statement as below:
# Recommended
if x>5 and x%2==0:
print('x is larger than 5 and divisible by 2!')
You are free to choose which is clearer, with the caveat that you must use the
same amount of whitespace either side of the operator.
list[3:4]
In some cases, adding whitespace can make code harder to read. Too much
whitespace can make code overly sparse and difficult to follow. PEP 8 outlines
very clear examples where whitespace is inappropriate.
The most important place to avoid adding whitespace is at the end of a line.
This is known as trailing whitespace. It is invisible and can produce errors
that are difficult to trace.
The following list outlines some cases where you should avoid adding
whitespace:
# Not recommended
my_bool = 6 > 5
if my_bool == True:
return '6 is bigger than 5'
The use of the equivalence operator, ==, is unnecessary here. bool can only
take values True or False. It is enough to write the following:
# Recommended
if my_bool:
return '6 is bigger than 5'
This way of performing an if statement with a Boolean requires less code and
is simpler, so PEP 8 encourages it.
Use the fact that empty sequences are falsy in if statements. If you want
to check whether a list is empty, you might be tempted to check the length of
the list. If the list is empty, it’s length is 0 which is equivalent to False when
used in an if statement. Here’s an example:
# Not recommended
my_list = []
if not len(my_list):
print('List is empty!')
However, in Python any empty list, string, or tuple is falsy. We can therefore
come up with a simpler alternative to the above:
# Recommended
my_list = []
if not my_list:
print('List is empty!')
While both examples will print out List is empty!, the second option is
simpler, so PEP 8 encourages it.
Use is not rather than not ... is in if statements. If you are trying to check
whether a variable has a defined value, there are two options. The first is to
evaluate an if statement with x is not None, as in the example below:
# Recommended
if x is not None:
return 'x exists!'
A second option would be to evaluate x is None and then have
an if statement based on not the outcome:
# Not recommended
if not x is None:
return 'x exists!'
While both options will be evaluated correctly, the first is simpler, so PEP 8
encourages it.
Don’t use if x: when you mean if x is not None:. Sometimes, you may
have a function with arguments that are None by default. A common mistake
when checking if such an argument, arg, has been given a different value is to
use the following:
# Not Recommended
if arg:
# Do something with arg...
This code checks that arg is truthy. Instead, you want to check that arg is not
None, so it would be better to use the following:
# Recommended
if arg is not None:
# Do something with arg...
The mistake being made here is assuming that not None and truthy are
equivalent. You could have set arg = []. As we saw above, empty lists are
evaluated as falsy in Python. So, even though the argument arg has been
assigned, the condition is not met, and so the code in the body of
the if statement will not be executed.
# Not recommended
if word[:3] == 'cat':
print('The word starts with "cat"')
However, this is not as readable as using .startswith():
# Recommended
if [Link]('cat'):
print('The word starts with "cat"')
Similarly, the same principle applies when you’re checking for suffixes. The
example below outlines how you might check whether a string ends in jpg:
# Not recommended
if file_name[-3:] == 'jpg':
print('The file is a JPEG')
While the outcome is correct, the notation is a bit clunky and hard to read.
Instead, you could use .endswith() as in the example below:
# Recommended
if file_name.endswith('jpg'):
print('The file is a JPEG')
As with most of these programming recommendations, the goal is readability
and simplicity. In Python, there are many different ways to perform the same
action, so guidelines on which methods to chose are helpful.
Linters
Linters are programs that analyze code and flag errors. They provide
suggestions on how to fix the error. Linters are particularly useful when
installed as extensions to your text editor, as they flag errors and stylistic
problems while you write. In this section, you’ll see an outline of how the
linters work, with links to the text editor extensions at the end.
$ pycodestyle [Link]
[Link]:17: E231 missing whitespace after ','
[Link]:21: E231 missing whitespace after ','
[Link]:19: E711 comparison to None should be 'if cond is None:'
flake8 is a tool that combines a debugger, pyflakes, with pycodestyle.
$ flake8 [Link]
[Link]:17: E231 missing whitespace after ','
[Link]:21: E231 missing whitespace after ','
[Link]:17: E999 SyntaxError: invalid syntax
[Link]:19: E711 comparison to None should be 'if cond is None:'
An example of the output is also shown.
Autoformatters
Autoformatters are programs that refactor your code to conform with PEP 8
automatically. Once such program is black, which autoformats code
following most of the rules in PEP 8. One big difference is that it limits line
length to 88 characters, rather than 79. However, you can overwrite this by
adding a command line flag, as you’ll see in an example below.
for i in range(0,3):
for j in range(0,3):
if (i==2):
print(i,j)
You can then run the following command via the command line:
$ black [Link]
reformatted [Link]
All done! ✨ 🍰 ✨
[Link] will be automatically reformatted to look like this:
Another Real Python tutorial, Python Code Quality: Tools & Best Practices by
Alexander van Tol, gives a thorough explanation of how to use these tools.
Conclusion
You now know how to write high-quality, readable Python code by using the
guidelines laid out in PEP 8. While the guidelines can seem pedantic, following
them can really improve your code, especially when it comes to sharing your
code with potential employers or collaborators.
On top of all this, you also saw how to use linters and autoformatters to check
your code against PEP 8 guidelines.