How to write compliant Python code
-
How to Write Beautiful Python Code With PEP 8
-
Jasmine Finer
-
Translation: howie6879
The directory is as follows:
-
Why We Need PEP 8
-
Naming Conventions
-
Naming Styles
-
How to Choose Names
-
Code Layout
-
Blank Lines
-
Maximum Line Length and Line Breaking
-
Indentation
-
Tabs vs. Spaces
-
Indentation Following Line Breaks
-
Where to Put the Closing Brace
-
Comments
-
Block Comments
-
Inline Comments
-
Documentation Strings
-
Whitespace in Expressions and Statements
-
Whitespace Around Binary Operators
-
When to Avoid Adding Whitespace
-
Programming Recommendations
-
When to Ignore PEP 8
-
Tips and Tricks to Help Ensure Your Code Follows PEP 8
-
Linters
-
Autoformatters
-
Conclusion
PEP8, also pronounced PEP8 or pep-8, is a document that provides guidelines and best practices on how to write Python code. It was written by Guido vanRossum,Barry Warsaw, and NickCoghlan in 2001. PEP 8 focuses on improving readability and consistency in Python code.
A PEP is a document that describes new features proposed for Python as well as documentation on aspects of Python, such as design and style, written for the community.
This tutorial Outlines the key guidelines outlined in PEP8 and is aimed at beginning to intermediate programmers, so I didn’t cover some of the top topics. But you can read the full PEP 8 – Style Guide for Python Code | Python.org document to study advanced topics.
By the end of this tutorial, you will be able to:
-
Write code that complies with the PEP 8 specification
-
Understand the reasons behind the guidelines listed in PEP 8
-
Set up your development environment to start writing Python code that complies with THE PEP 8 standard
Why We Need PEP 8
Readability is important
The PEP8 specification exists to make Python code more readable, but why is readability so important? Why is writing readable code one of the guiding principles of the Python language?
As GuidovanRossum said, “code is read far more often than it is written.” You may spend a few minutes or a whole day writing a piece of code that handles user authentication, and once you’ve written it, you’ll never rewrite it again, but you’ll certainly read it again, and it may still be part of your ongoing project. Every time you go back to that code file, you have to remember what that piece of code does and why you wrote it, so readability is important.
If you are new to Python, it may be difficult to remember the meaning of code snippets days or weeks after you write them. If you follow PEP8 standard, you can be sure of your variable naming is very good, you will know that you add enough space, so it is easier to follow the logical steps in your code, you can also code for you good comments, all of this means that you have higher the readability of the code, it will be easier to read again. As a beginner, following the rules of PEP 8 can make learning Python a more enjoyable task.
If you’re looking for a job, it’s especially important to follow PEP8. Writing clear, readable code will show your boss that you know how to build your code well.
If you have a lot of experience of Python code, then you may need and others collaborative development, here to write readable code is crucial, others may never before seen you this style code, he must to read and understand your code style, if have you follow the guide and recognition will make it easier for others to read your code.
Naming Conventions
Clarity is better than obscurity
When you write Python code, you have to name a lot of things: variables, functions, classes, packages, etc. Choosing the right names will save you time and effort. You will be able to figure out what a variable, function, or class represents from its name. You also want to avoid using inappropriate names, as this can lead to hard-to-debug errors.
::Note: Never use I, O, or I single-letter names, as these may be mistaken for 1 and 0, depending on the font :::
# This might look like you're trying to reassign 2 to zero
0 = 2
Copy the code
Naming Styles
The following table summarizes some common naming styles in Python code and when they should be used:
These are some common naming conventions and examples of how to use them, but you still need to choose letters and words carefully in order to write highly readable code. In addition to choosing the right naming style in your code, you must also choose names carefully, and here are some instructions on how to do this as efficiently as possible.
How to Choose Names
Choosing names for variables, functions, classes, and so on can be a challenge, and you should put a fair amount of thought into your naming choices when writing code because it makes your code more readable. The best way to name objects in Python is to use descriptive names that make it clear what the object represents.
When naming variables, you might choose simple single-letter lowercase names, such as x. But unless you use x as an argument to a mathematical function, it’s not clear what x stands for. Imagine that you are saving a person’s name as a string, and you want to format the name using string slices. You end up with something like this:
# Not recommended
x = 'John Smith'
y, z = x.split()
print(z, y, sep=', ')
# 'Smith, John'
Copy the code
The above code works fine, but you have to keep track of what x,y, and z mean, which can also confuse your code collaborators. A more explicit name choice would look like this:
# Recommended
name = 'John Smith'
first_name , last_name = name.split ()
print (last_name, first_name, sep= ', ')
# 'Smith, John'
Copy the code
Similarly, it is tempting to use abbreviations when choosing names in order to reduce the number of inputs. In the following example, I define a function db() that takes an argument x and doubles it back:
# Not recommended
def db(x ):
return x * 2
Copy the code
At first glance, this seems a sensible choice. It’s easy to think of db() as an abbreviation for double, but imagine looking at this code a few days later and forgetting what you were trying to accomplish with this function, which would make guessing what it originally meant difficult.
If you look at the code a few days later, you can still read and understand the purpose of this function:
# Recommended
def multiply_by_two(x):
return x * 2
Copy the code
The same idea applies to all other data types and objects in Python, always using the most concise and descriptive names possible.
Code Layout
Beauty is better than ugliness
How your code is laid out can make a big difference in its readability. In this section, you’ll learn how to add vertical whitespace to improve the readability of your code. You’ll also learn how to deal with the 79 character line limit recommended in PEP8.
Blank Lines
Vertical whitespace or blank lines can greatly improve the readability of code, which can be overwhelming and difficult to read. Similarly, too many blank lines in code can make it look sparse and the reader may need to scroll unnecessarily. Here are three key guidelines for using vertical whitespace.
Enclosing the top-level functions and classes with two empty lines, the top-level functions and classes should be completely self-contained and handle separate functions, and it makes sense to place extra vertical space around them, so it’s obvious they’re separate:
class MyFirstClass:
pass
class MySecondClass:
pass
def top_level_function():
return None
Copy the code
Enclose a method definition in a class with an empty line. In a class where functions are related to each other, it is best to leave only one line between them:
class MyClass:
def first_method(self):
return None
def second_method(self):
return None
Copy the code
Use empty lines carefully inside functions to show clear steps. Sometimes a complex function must complete several steps before a return statement. To help the reader understand the logic inside a function, it is helpful to leave a blank line between each step.
In the example below, where there is a function that calculates the variance of a list, the problem can be divided into two steps, so I leave a blank line between each step and a blank line before the return statement. This helps the reader see clearly what is being 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)
return mean_squares - mean**2
Copy the code
Vertical whitespace, if used carefully, can greatly improve the readability of your code, and it can help readers visualize how your code is broken up into sections and how those sections relate to each other.
Maximum Line Length and Line Breaking
PEP8 recommends limiting each line of code to 79 characters because it allows multiple files to be opened side by side and also avoids line breaks. Of course, keeping statements to 79 characters is not always possible. PEP 8 Outlines ways to allow statements to run on multiple lines.
If code is enclosed in parentheses, square brackets, or braces, Python will treat the code as a single line:
def function(arg_one, arg_two,
arg_three, arg_four):
return arg_one
Copy the code
If per-line continuations are not possible in the same way, backslashes can be used instead of newlines:
from mypkg import example1, \
example2, example3
Copy the code
However, if you can use the first scenario, you should try to do so.
If you need to do line breaks around binary operators, such as + and *, you need to put the line breaks first. This rule comes from mathematics. Mathematicians agree that line breaks precede binary operators to improve readability.
Here is an example of a line break before a binary operator:
# Recommended
total = (first_variable
+ second_variable
- third_variable)
Copy the code
You can immediately tell which variables are adding and which are subtracting, because the operators are adjacent to the variables.
Now, let’s look at an example of a line break after a binary operator:
# Not Recommended
total = (first_variable +
second_variable -
third_variable)
Copy the code
Here, it’s hard to see which variable is being added and which is being subtracted.
Line breaks before binary operators make code more readable, which PEP8 encourages. Code that wraps after a binary operator still conforms to PEP 8, but you are encouraged to wrap before the binary operator.
Indentation
When multiple possibilities exist, don’t try to guess but try to find one, preferably the only obvious solution (if in doubt, use brute force)
Indentation, or leading whitespace, is very important in Python. The indentation level of lines of code in Python determines how statements are put together.
Consider the following example:
x = 3
if x > 5:
print('x is larger than 5')
Copy the code
The indented print statement makes Python understand that an if statement must return True to proceed, and the same indenting applies to telling Python which code to execute when calling a function, or which code belongs to a given class.
The key indentation rules laid down by PEP8 are as follows:
-
Use 4 consecutive Spaces to indicate indentation.
-
Select Spaces instead of tabs.
Tabs vs. Spaces
As mentioned above, you’re better off using Spaces instead of tabs when you indent. You can directly adjust the text editor Settings to convert the output to four Spaces when you press Tab
If you’re using Python 2 and use a mix of tabs and Spaces to indent code, you probably won’t see errors when you run it. To help you check for consistency, add the -t flag when you run Python 2 code from the command line. The interpreter will issue a warning when you use tabs and Spaces inconsistently:
python2 -t code .py
code .py : inconsistent use of tabs and spaces in indentation
Copy the code
Conversely, if you use the -tt flag, the interpreter will issue an error instead of a warning. The advantage of using this method is that the interpreter will tell you where the indentation is inconsistent:
python2 -tt code .py
File "code.py" , line 3
print( i, j)
^
TabError : inconsistent use of tabs and spaces in indentation
Copy the code
Python3 does not allow a mixture of tabs and Spaces, so if you are using Python3, the interpreter will automatically report an error:
python3 code.py
File "code.py", line 3
print(i, j)
^
TabError: inconsistent use of tabs and spaces in indentation
Copy the code
You can write Python code using tabs or Spaces to indicate indentation, but if you’re using Python 3, it must be consistent with your choice, or your code won’t work. PEP8 recommends that you always use 4 consecutive Spaces to indicate indentation.
Indentation Following Line Breaks
Indentation is useful to improve readability when wrapping lines to keep them under 79 characters. It allows the reader to distinguish between two lines of code and a single line that spans two lines. There are two indentation styles you can choose from.
The first is to align the indent block with the opening delimiter:
def function(arg_one, arg_two,
arg_three, arg_four):
return arg_one
Copy the code
Sometimes you’ll find that only 4 Spaces are needed to align with the open delimiter. This often happens in if statements that span multiple lines of if++(forming 4 characters), in which case it’s hard to determine where the nested code block in an if statement starts:
x = 5
if (x > 3 and
x < 10):
print(x)
Copy the code
In this case, PEP8 offers two alternatives to help you improve code readability:
-
Add a comment after the last condition. Since most editors have syntax highlighting, this separates the condition from the nested code:
x = 5
if (x > 3 and
x < 10):
# Both conditions satisfied
print(x)
Copy the code
-
Add extra indentation to a line feed:
x = 5
if (x > 3 and
x < 10):
print(x)
Copy the code
Another way to indent after a line break is hanging indent. This is a printing term that means that every line in a paragraph or statement is indent except for the first line. You can use hanging indent to visually indicate the continuation of a line of code. Here’s an example:
var = function (
arg_one , arg_two ,
arg_three , arg_four )
Copy the code
::Note: When you are using hanging indent, the first line must not have any parameters. The following example does not comply with PEP 8::
# Not Recommended
var = function(arg_one, arg_two,
arg_three, arg_four)
Copy the code
When you use Hanging indent, you can add additional indentation to distinguish between consecutive lines and code contained within a function. Here’s an example that’s hard to read because the code inside the function has the same level of indentation as the consecutive lines:
# Not Recommended
def function(
arg_one, arg_two,
arg_three, arg_four):
return arg_one
Copy the code
Instead, it’s best to use double indentation after a line wrap. This helps you distinguish between function arguments and function internals, thus improving readability:
def function(
arg_one, arg_two,
arg_three, arg_four):
return arg_one
Copy the code
When you write code that complies with the PEP8 specification, the rule of 79 characters per line forces you to break lines. For readability, you should indent one line to indicate that it is a continuous line. There are two ways to do this. The first is to align the indented block with the starting delimiter, and the second is to use hanging indentation. After a line break, you are free to use either method for indentation.
Where to Put the Closing Brace
One line of code wrapping operation allows you to behind the parentheses, square brackets, or braces off line, this creates a problem, is easy to forget the closing bracket, but it is important to put it in a reasonable place, otherwise, it will make readers confused, Pep8 for hidden line of the position of the closing parenthesis offers two options:
-
Arrange the close parentheses using the first non-whitespace character of the previous line:
list_of_numbers = [
1, 2, 3,
4, 5, 6,
7, 8, 9
]
Copy the code
-
Align the closing parenthesis with the first character of the declaration line:
list_of_numbers = [
1, 2, 3,
4, 5, 6,
7, 8, 9
]
Copy the code
You are free to go either way, but, as mentioned earlier, consistency is key, so stick to one of the solutions you choose to keep your code consistent.
Comments
If you can’t describe your plan, it’s not a good plan. And vice versa
You should use comments to explain the code you are writing, which is very important for documenting your code so that any of your collaborators can understand it. When you or someone else reads a code comment, they should be able to easily understand the code to which the comment applies and how it fits with the rest of the code.
Here are some key points to note when commenting your code:
-
Limit comment and docstring lines to 72 characters
-
Use complete sentences, beginning with a capital letter
-
Comments are updated as the code is updated
Block Comments
Use block comments to record small pieces of code, which are useful when you have to write several lines of code to perform a single operation, such as importing data from a file or updating a database record. They are important because they help others understand the purpose and function of a given block of code.
PEP8 provides the following rules for writing notes:
-
Indent a block comment to the same level that it describes the code
-
Comment each line with a # followed by a space
-
Separate paragraphs with lines containing a single #
Here is a block comment explaining the functionality of the for loop. Note that the sentence is wrapped to preserve the 79 character line limit per line:
for i in range(0, 10):
# Loop over i ten times and print out the value of i, followed by a
# new line character
print(i, '\n')
Copy the code
Sometimes, if the code is more technical, it may be necessary to use multiple paragraphs in block comments:
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
Copy the code
If you’re not sure what type of comment is appropriate, block comments are usually the right choice. Please add comments to your code as much as possible, and be sure to update the comments as soon as you update the code!
Inline Comments
Inline comments explain a piece of code in a single statement. They help remind you or others why a particular line of code is necessary. Here’s what PEP8 says about them:
-
Use inline comments with caution
-
Write in-line comments on the same lines as the statements they reference
-
Separate inline comments from statements with two or more Spaces
-
Like block comments, start each line with # plus a space
-
Don’t use them to explain the obvious
Here is an example of an inline comment:
x = 5 # This is an inline comment
Copy the code
Sometimes inline comments seem necessary, but you can use better naming conventions. Here’s an example:
x = 'John Smith' # Student Name
Copy the code
Here, inline comments provide additional explanatory information for variables, but it’s not a good practice to use x as a variable name for a person’s name. If you rename variables, you don’t have to use inline comments:
student_name = 'John Smith'
Copy the code
Finally, inline comments like these are bad practice because they state obvious and cluttered code:
empty_list = [] # Initialize empty list
x = 5
x = x * 5 # Multiply x by 5
Copy the code
In-line comments are more specific than block comments, and it’s easy to add them unnecessarily, which can lead to code clutter. Unless you’re sure you need in-line comments, it’s better to use block comments to avoid code clutter. Stick with block comments to make your code more PEP8 compliant.
Documentation Strings
Documentationstrings, or Docstrings, are strings enclosed in double (” “) or single (” “) quotation marks that appear on the first line of any function, class, method, or module, and you can use them to interpret and record specific blocks of code. There is a corresponding PEP, see PEP 257, but you can read the lessons learned in this section:
Important rules for using docstrings are as follows:
-
The docstring is surrounded by three double quotes, such as: “””This is a docString “””
-
Write docStrings for all public modules, functions, classes, and methods
-
Use a single line “” to end a multi-line docString
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
Copy the code
-
For single-line docstrings, keep “”” on the same line:
def quadratic(a, b, c, x):
"""Use the quadratic formula"""
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
Copy the code
To learn more, read Documenting Python Code: A Complete Guide – Real Python
Whitespace in Expressions and Statements
Space is better than compact
Using white space correctly is very useful in expressions and statements. If you don’t have enough white space in your code, it should be hard to read because they all come together. If you have too much white space, it will be hard to visually relate the entire statement.
Whitespace Around Binary Operators
A space should be added to both sides of the binary operation:
-
Assign operations (=, +=, -=, etc.)
-
Compare (==,! =, >, <. >=, <=) and (is, is not, in, not in)
-
Boolean (and, not, or)
::Note: When = is assigned to a function parameter, do not use Spaces ::
# Recommended
def function( default_parameter= 5):
#...
# Not recommended
def function( default_parameter = 5 ):
#...
Copy the code
If there are multiple operators in a statement, it can be confusing to add a single space before and after each operator. Instead, it is best to add Spaces only around the lowest-priority operators, especially when performing mathematical operations. Here are a few examples:
# Recommended
y = x**2 + 5
z = (x+y) * (x-y)
# Not Recommended
y = x ** 2 + 5
z = (x + y) * (x - y)
Copy the code
You can also apply this to if statements with multiple conditions:
# Not recommended
if x > 5 and x % 2 == 0:
print('x is larger than 5 and divisible by 2! ')
Copy the code
In the example above, the AND operation has the lowest priority, so the if statement can be expressed more clearly as follows:
# Recommended
if x> 5 and x %2 ==0 :
print( 'x is larger than 5 and divisible by 2! ')
Copy the code
You are free to choose which is clearer, but note that you must use the same number of Spaces on either side of the operator.
The following example is not allowed:
# Definitely do not do this!
if x >5 and x% 2== 0:
print('x is larger than 5 and divisible by 2! ')
Copy the code
In slicing, the colon is used as a binary operator. Therefore, the rules outlined in the previous section also apply here, and there should be the same amount of white space on either side, and the following list slice example is legal:
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 :]
Copy the code
In general, you should surround most operators with Spaces, however, there are a few caveats to this rule, such as when combining multiple operators in function arguments or in a single statement.
When to Avoid Adding Whitespace
In some cases, adding whitespace can make the code hard to read, and too many whitespace can make the code too sparse to understand. PEP8 Outlines some very obvious examples where Spaces should be left out
Avoiding adding Spaces at the end of a line is most important. This is called trailing whitespace, which is not visible and can result in hard-to-trace errors.
The following list Outlines some situations where adding whitespace should be avoided:
-
Placed directly within brackets, square brackets, or braces:
# Recommended
my_list = [1, 2, 3]
# Not recommended
my_list = [ 1, 2, 3, ]
Copy the code
-
Before a comma, semicolon, or colon:
x = 5
y = 6
# Recommended
print(x, y)
# Not recommended
print(x , y)
Copy the code
-
Before opening the parentheses on the argument list of a function call:
def double(x):
return x * 2
# Recommended
double(3)
# Not recommended
double (3)
Copy the code
-
Before opening parentheses for indexing or slicing:
# Recommended
list[3]
# Not recommended
list [3]
Copy the code
-
Between trailing comma and closing parenthesis:
# Recommended
tuple = (1,)
# Not recommended
tuple = (1, )
Copy the code
-
Align assignment operators:
# Recommended
var1 = 5
var2 = 6
some_long_var = 7
# Not recommended
var1 = 5
var2 = 6
some_long_var = 7
Copy the code
Make sure there are no trailing Spaces in your code. In other cases, PEP8 discourages the addition of additional Spaces, such as standing directly inside parentheses, square brackets, or braces, and before commas and colons. Additional Spaces should also not be added to align operators.
Programming Recommendations
Simplicity is better than complexity
You’ll often find several ways to do something similar in Python (and any other programming language). In this section, you’ll see some of PEP8’s recommendations for disambiguating and maintaining consistency.
Do not use equivalent operators to compare booleans to True or False. You often need to check whether booleans are True or False. When doing so, do this visually using statements like this:
# Not recommended
my_bool = 6 > 5
if my_bool == True :
return '6 is bigger than 5'
Copy the code
Instead of using the equivalent operator ==, bool can only be True or False, as follows:
# Recommended
if my_bool:
return '6 is bigger than 5'
Copy the code
This way of using bool in an if statement writes less code and is simpler, so PEP8 encourages it.
When you want to determine if the list is empty, you usually determine the length of the list. If the list is empty, then the length is 0, which equals False when used in the if statement. Here is an example:
# Not recommended
my_list = []
if not len( my_list):
print( 'List is empty! ')
Copy the code
However, in Python, any empty list, string, or tuple can be False. Therefore, we can propose a simpler alternative:
# Recommended
my_list = []
if not my_list:
print('List is empty! ')
Copy the code
Both methods can tell if the list is empty, but the second method is more concise, which is why PEP8 encourages it.
In an if statement, use is not better than no… When you need to determine whether a variable is assigned, there are two ways to do so. The first way is to evaluate if x in the if statement is not None, as follows:
# Recommended
if x is not None :
return 'x exists! '
Copy the code
The second option is to now check if x is None and then not:
# Not recommended
if not x is None :
return 'x exists! '
Copy the code
Both methods can determine whether x is None, but the first is simpler, so PEP 8 encourages it.
Do not use if x when you want to say if x is not None. Sometimes, you may have a function with an argument that defaults to None. The following error is often made when checking arg for different values:
# Not Recommended
if arg:
# Do something with arg...
Copy the code
This code checks if arg is true, but instead you want to check if arG is None, so it’s better to write it like this:
# Recommended
if arg is not None :
# Do something with arg...
Copy the code
You can set arg =[]. As mentioned above, empty lists are considered False in Python. Therefore, although the argument is declared as [], the condition is not met, so the if declaration in the function cannot be executed.
Instead of slicing, use.startswith() and.endswith(). If you want to check whether a string prefix or suffix has the string cat, it might seem wise to use list slicing. However, list slicing is error-prone and you must hardcode the number of characters in the prefix or suffix. For those unfamiliar with Python list slicing, it’s hard to see what you’re trying to accomplish:
# Not recommended
if word[: 3] == 'cat' :
print( 'The word starts with "cat"')
Copy the code
However, use.startswith(): it is more readable:
# Recommended
if word. startswith( 'cat'):
print( 'The word starts with "cat"')
Copy the code
The same principle applies when you want to check string suffixes. The following example Outlines how to check if a string ends in JPG:
# Not recommended
if file_name[-3:] == 'jpg':
print('The file is a JPEG')
Copy the code
Although the result is correct, the notation is a bit complicated and difficult to read, as opposed to.endswith(), as in the following example:
# Recommended
if file_name. endswith( 'jpg'):
print( 'The file is a JPEG')
Copy the code
As with the programming advice listed above, the goal is to write clean and readable code. In Python, there are many different ways to achieve the same result, so a guide on which method to choose is helpful.
When to Ignore PEP 8
When to ignore PEP 8? The short answer to that question is never
If you follow PEP 8 closely, you can ensure that you have clean, professional, and readable code. This benefits you as well as your collaborators and potential employers.
However, some of the guidelines in PEP 8 do not apply in the following instances:
-
Compliance with PEP 8 breaks compatibility with existing software
-
If you are working on code that is inconsistent with PEP 8
-
If the code needs to be compatible with older Python versions
Tips and Tricks to Help Ensure Your Code Follows PEP 8
There are quite a few specifications you need to remember to make your code PEP8 compliant, and remembering all of them can be a daunting task when developing code. Especially when updating older projects to be compatible with PEP 8. Fortunately, there are tools that can help you speed up the process. Here are two tools that can help you enforce compliance with the PEP 8 specification: Linters and Autoformatters.
Linters
Linters are programs that analyze code and mark errors. They can give you advice on how to fix errors, and are especially useful when installed as extensions to a text editor because they can mark errors and formatting problems when you program. In this section, you’ll see an outline of how Linters programs work, with a link to text editor extensions at the end.
For Python code, the best linters are shown below:
-
Pycodestyle is a tool for checking Python code against certain style conventions in PEP 8
# Install PyCodeStyle with PIP
pip install pycodestyle
Copy the code
Use pyCodeStyle on the terminal with the following command:
pycodestyle code .py
code .py :1 :17 : E231 missing whitespace after ','
code .py :2 :21 : E231 missing whitespace after ','
code .py :6 :19 : E711 comparison to None should be 'if cond is None:'
Copy the code
-
Flake8 is a tool that combines debugger, PyFlakes and PyCodeStyle
# Install Flake8 using PIP
pip install flake8
Copy the code
Use pyCodeStyle on the terminal with the following command:
flake8 code .py
code .py :1 :17 : E231 missing whitespace after ','
code .py :2 :21 : E231 missing whitespace after ','
code .py :3 :17 : E999 SyntaxError : invalid syntax
code .py :6 :19 : E711 comparison to None should be 'if cond is None:'
Copy the code
Examples of the output are also shown.
::Note: An extra line of output indicates a syntax error. : :
These are also available as extensions to Atom, Sublime Text, Visual Studio Code, and VIM. You’ll also find a guide to setting up Sublime Text and VIM for Python development, as well as an overview of some of the popular Text editors in Real Python.
Autoformatters
Autoformatters can refactor your code to conform to the PEP 8 specification. Programs like Black can reformat your code according to the PEP 8 specification. One big difference is that it limits the line length to 88 characters instead of 79 characters. However, you can override it by adding command line flags, as shown in the following example.
You can install black using PIP, which requires Python3.6+ :
pip install black
Copy the code
It can be run from the command line, like Linters. Suppose you start with code named code.py that doesn’t comply with the PEP 8 specification:
For I in range (0, 3) :
For j in range (0, 3) :
if (i==2):
print(i,j)
Copy the code
You can run the following code from the command line:
black code . py
reformatted code . py
All done !
Copy the code
Code.py will be reformatted as follows:
for i in range ( 0 , 3 ):
for j in range ( 0 , 3 ):
if i == 2 :
print ( i , j )
Copy the code
If you want to change the line length limit, you can use the -line-length flag:
black -- line - length = 79 code . py
reformatted code . py
All done !
Copy the code
The other two AutoFormatters are Autopep8 and YAPf, which are similar to the black operation.
Another Real Python tutorial, Python Code Quality: Tools & Best Practices by Alexander Van Tol, explains how to use these Tools in detail.
Conclusion
You now know how to write high-quality, readable Python code using the guidelines in PEP 8, and while the guidelines may seem pedantic, following them can really improve your code, especially when sharing code with potential employers or collaborators.
In this tutorial you learn:
-
What is PEP 8 and why is it there
-
Why should you write code that complies with PEP 8
-
How do I write CODE that is PEP 8 compliant
In addition, you learned how to use Linters and Autoformatters to check code according to the PEP 8 guide.
If you want to learn more, you can read Full Documentation or visit PEP8.org. These tutorials not only provide similar information but also provide a good format for you to read. In these documents, you will find the rest of the PEP 8 guides that are not covered in this tutorial.
Translation is not easy, please forward as well as click on the lower right corner to see support ^_^
Previous recommendations:
Sanic Chinese tutorial collection: free download
How do I create a simple neural network in Python
Python decorator