What is PEP8 ?
We have seen several topics on Python in my previous articles (here). Today, we will discuss about PEP8 convention. ๐
PEP8 is coding conventions for the Python code comprising the standard library in the main Python distribution.
It exists to improve the readability of Python code. As you know, we spend more time reading code than coding !
You can find all the documetation here but I will try to help you save some time by giving you 10 simples rules ๐
My 10 rules to respect PEP8 Conventions
1. Naming Styles
For each of the following identifier, you have to respect the following convention :
2. Blank Lines
Surround top-level functions and classes with two blank lines :
class MyFirstClass:
pass
class MySecondClass:
pass
def top_level_function():
return None
3. Don’t use some characters as variables
Never use l, O, or I single letter names as these can be mistaken for 1 and 0. Avoid using inappropriate names that might result in errors that are difficult to debug.
4. Use Spaces
Use spaces, not tabs ! Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.
5. Short Lines
Lines mustn’t have more than 79 characters. For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.
6. Comments
- Use complete sentences, starting with a capital letter.
- Make sure to update comments if you change your code.
- Limit the line length of comments and docstrings to 72 characters (or use blocks).
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')
7. Imports convention
Imports should usually be on separate lines:
import os
import sys
8. Remove useless spaces in statements
Remove whitespaces in statements, i.e :
# wrong
func( data, { pivot: 4 } )
# ok
func(data, {pivot: 4})
9. Donโt compare boolean values to True or False
It is intuitive to do this with a statement like the one below :
# Not recommended
my_bool = 6 > 5
if my_bool == True:
return '6 is bigger than 5'
# Recommended
if my_bool:
return '6 is bigger than 5'
10. Check if your code is compliant !
The pep8 package intends to search for PEP-8 incompatibility in your code and suggests changes that you can make to make your code follow the PEP-8.You can install pep8 module using pip.
Example :
$ pep8 --first optparse.py
optparse.py:69:11: E401 multiple imports on one line
optparse.py:77:1: E302 expected 2 blank lines, found 1
optparse.py:88:5: E301 expected 1 blank line, found 0
optparse.py:222:34: W602 deprecated form of raising exception
optparse.py:347:31: E211 whitespace before '('
optparse.py:357:17: E201 whitespace after '{'
optparse.py:472:29: E221 multiple spaces before operator
optparse.py:544:21: W601 .has_key() is deprecated, use 'in'
Sources
python.org
datacamp.com
realpython.com