Writing Clean Code in Python : PEP-8 Guidance & Tools
Python is one of many programming language that can be used for software development, data analysis, and artificial Intelligence. In practically when we use python to build or analyze data, there are many problem occured when our code is getting more complex.
Writing code is not just about writing correct logic, it’s also about formatting it in a consistent way so that it can be reusable, optimized, and understandable.
In this article, I will explain how to apply standard guidelines for python code using PEP 8 and tools to tidy up our code according to the PEP 8 standard.
PEP-8 : Style Guide for Python Code
PEP 8 is a document that provides rules on how to write standard-compliant Python code. PEP 8 is used to improve the readability of the python code. This is important to do when we create huge projects and especially when we collaborate with others. By making readable code that is according to standards, it allows other people to read and understand the code. Some examples of PEP 8 rules is how we create naming variables, creating comments, describing functions and so on.
Basic Formatting / Code Layout
- Indentation
Use 4 spaces per indentation level.
- Maximum Line Length
Limit all lines to a maximum of 79 characters.
- Blank Lines
When creating a function, class, or method in a class, it must be given a blank line with the following number :
- Class & main function : 2 blank lines,
- Function : 1 blank lines,
- Method : 1 blank lines
- Whitespaces usage
Whitespaces usage on statements and expressions :
- Imports
When we need import module / library, we can use this standards :
- Imports of several modules must be distinguished on each line, except for sub-functions in a module.
- Import order follows this rule :
- Standard library imports.
- Related third party imports.
- Local application/library specific imports.
- Error Handling
When using try and except, use clear exceptions.
Naming Guidelines
The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used. Robert C. Martin
In general, there is guidance when we initiate/declare name for variable.
- Avoid naming variables with meaningless/random letters.
Bad :
seq = (“Austin”, “New York”, “San Francisco”)for item in seq: #do_stuff()
Good :
locations = (“Austin”, “New York”, “San Francisco”)for location in locations: #do_stuff()
- Use a name that expresses a specific function / activity.
Good : getFlaggedCells()
- Avoid naming using abbreviations.
Bad :
get_cur_mnthyr()
Good :
get_current_month_year()
- Class & Object : noun; Method / Function : verb
# Class name
class Book :
.... # Method name
get_book():
- Using variable names that are easy to find.
Bad :
time.sleep(86400)
Good :
SECONDS_IN_A_DAY = 60 * 60 * 24time.sleep(SECONDS_IN_A_DAY)
- Using one standard word for the same entity.
Bad :
def get_user_info(): passdef get_client_data(): passdef get_customer_record(): pass
Good :
def get_user_info(): passdef get_user_data(): passdef get_user_record(): pass
- Use one of the naming conventions :
- b (single lowercase letter)
- B (single uppercase letter)
- lowercase
- lower_case_with_underscores
- UPPERCASE
- UPPER_CASE_WITH_UNDERSCORES
- CapitalizedWords
- mixedCase
Python Tools formating based on PEP-8
I know it’s hard to remember all of PEP 8 guidance to make our code clean and standardized. Because there is many guidance that we must follow and remember. But, there are tools that can help speed up this process. There are two classes of tools that you can use: linters and autoformatters.
Linters
Linters are tools that can detect and flag our code when it doesn’t meet the PEP-8 standards. Usually we can install linters as extensions to our text editor (i.e Visual Studio Code). Also linters can provide suggestion to fix the error. One of popular linters is pycodestyle, we can install and add the extensions to our visual studio and automatically check our Python code against some of the style conventions in PEP 8.
Autoformatters
After we know our error based on linting, we can fix manually one by one. But there is Autoformatters that can automatically refactor our code to conform with PEP 8 . an example of an autoformatter tool that can be used is AutoPep8.
- Install Autopep8
pip install autopep8
- Refactor specified file
autopep8 --select=E1,W1 <filename>