Coding Standards and Best Practices for Python Code Quality

Coding Standards and Best Practices for Python Code Quality

If you just have started writing code, you would have surely been asked by professionals or your teacher to write it neat and clean or change the names of variables or at least would have asked to improve the documentation of the code. The reason for this much focus on code quality is because of the human mind, you would not understand your own code even after a few weeks if written improperly and that’s why code standards are developed to maintain the quality.
 

Python, by nature, is a well-structured language that separates the block of codes by Indentation. But still, there are several guidelines about code quality rules which should be maintained to produce a beautiful and easily understandable code. In this blog, I will discuss these standards and practices.

Have you heard about the Zen of Python? If not, go to the python console and type ‘import this’ and let’s see the output.

the-zen-of-python
 

The Zen of Python, written in 2004 by Tim Peters is a collection of 19 guiding principles on which Python works. It is included in PEP 20 of Python Enhancement Proposal (PEP). The python coding standards are mentioned in PEP8 of the same PEP. For coding standards, referencing the features of PEP8 is more than enough.

Use the features of PEP8 for Better Syntax

I will be explaining the crux of PEP8 here. If you want, you can go to visit the official site to read and understand each, and every aspect in detail, click here.

1. The Code layout:

This consists of Indentation, the maximum line length to be used, line breaks and blank lines, imports in python, and dunder names. Let’s discuss them with examples.

a. Imports, Blank Lines, and the Indentations:

The import should be in a particular sequence. At first, the standard libraries, then the third party, and at the last, the local libraries should be imported. If you only need a single function/class from the import, do an absolute import. It makes your code much cleaner, accurate, and easy to identify. Don’t forget to add a space between different types of imports.

There should be two blank lines surrounding classes and top-level functions. The methods inside of the class should be surrounded by a single blank line only. The preferred method of indentation is spaces, the 4 spaces indentation is accepted and accurate, but still, most people prefer tab indentation. Please keep in mind not to mix both spaces and tabs for indentation.

For Example:-


# Don't forget to add a space between different group of imports

# first of all, the standard library imports
import standard_library_import_a
import standard_library_import_b
    
# then,the third party imports
import third_party_import_a
import third_party_import_b
import third_party_import_c
    
# at the last, local library import
from local_library import local_a, local_b
from local_library_two import local_c
    
    
# two blank lines for top level functions
def top_level_function(argument):
# A standard four space indent
print(argument)

b. The length of the Line and the Line Breaks

The length of the line should not be greater than 79 characters. In the case of docstrings and comments where a block of text is large, it is limited to 72 characters. For long multiple case statements, the backslashes are permissible. For using log statements with binary operators, python suggests breaking the formula line before the binary operator for better readability.

For Example:-


def sample_function(arg1, arg2):

'''
The document string length for a single line should be less than
72 characters. So that long texts should be adjusted in a single
window
'''
    
# code has maximum lengths of 79 characters, can use backslash
# to break the line
list_of_subjects = [
'Physics', 'Chemistry', 'Mathematics', 'Biology',  ‘Bio’, \
]

2. Whitespaces, Trailing Commas, and String Quotes

One should avoid extra white spaces, there must be a single white space around both sides of an operator, one after the comma and none inside opening or closing of parenthesis. Both single quotes and double quotes are acceptable in python, you should use both if you need quotes inside quotes to avoid syntax error and extra backslash.

For Example:-


# Examples of commas and whitespaces
    
x,  y = 30,  "text inside quotes"
z = 'text inside quotes'
if x == 30: print(x, y, z)

# how to use quotes inside quotes
text = "This text is using 'the single quote' inside double quote"
print(text)



3. Naming Conventions

Use grammatically correct variable names, the class name should start with an uppercase and must follow camelCase convention If more than two words are to be used. In the same way, a function name should be joined with an underscore, and it must be lowercase. In method arguments, always use self as the first argument to declare an instance variable. In the same way, use ‘cls’ for the first argument for the class method. If the function name clashes with a reserved argument, use an underscore instead of a wrong spelling. Constants are declared in all capital letters.

For Example:-


# class name follows camelcase convention
class StudentDetails:
                
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
                
# Method name, variable names in lowercase joined with an underscore
def grade(self, marks_obtained):
# constants in capital
GRACE = 2
marks_obtained = GRACE + marks_obtained
if marks_obtained > 90:
self.student_grade = 'A'
elif marks_obtained > 70:
student_grade = 'B'
else:
student_grade = 'C'

Some other Coding Recommendations:

There are certain coding recommendations that should be kept in mind to be consistent with an errorless and quality of code. I will list down the points and then explain them later in the code.

1. Exception Handling for every critical situation

For Example:-


try:
file = open('filename.txt')
file.write('Hello World')
    
except Exception as e:
print('Cannot open the file :', e)
    
finally:
# Make sure to close the file after
file.close()


2. Documentation of a Method

Documenting every method with proper specification of parameters, return type, and data types. Try to avoid multiple returns from a function, a single generic return is preferred

For Example:-


# documenting a function
def get_grades(marks):
"""
Summary: getting grades from marks
Description: This function takes marks as an argument and returns grades
params:
marks(int) : marks obtained
:
grade(string) : grade achieved
"""
if marks > 90:
grade = 'A'
elif marks > 70:
grade = 'B'
else:
grade = 'C'
        
return grade

3. Use DRY (Don’t Repeat Yourself):

Always use the DRY principle to reuse the code. The best way to do it is to use functions and classes. The common functions can be put into a separate utils.py file and can be used several times instead of creating similar functions again and again.

Suppose if you need to read three files, instead of writing code for file read thrice, you can read it as a function and save your time.

For Example:-


# function to read the file read
def file_read(filename):
with open(filename, 'r') as f:
return f.read()

qualities = file_read('quality.txt')
description = file_read('description.txt')
summary = file_read('summary.txt')
      

4. What to use? Tuples, Lists of Dictionaries

Use tuples when data is non-changeable, dictionaries when you need to map things, and lists if your data can change later on.

For Example:-


# tuples are used when data is constant
colors_of_rainbow = ('V', 'I', 'B', 'G', 'Y', 'O', 'R')
    
# lists where data can be mutated
movies_to_watch  = ['Inception', 'Iron Man', 'Wonder Woman']
    
# Using lists in mapping is wrong
# O(n) time would be taken to extract marks
marks_obtained = [['History', 30], ['English', 35], ['Physics', 45]]
    
# dicts when mapping is needed
# dicts take O(1) time to get key value
marks_obtained = {'History': 30, 'English': 35, 'Physics': 45}
        

5. Use the ‘with’ statement while opening a file, the ‘with’ statement closes the file even if there is an exception raised

For Example:-


import csv

# opening a file, with statement is used
with open('filename.csv', 'r') as file:
csv_reader = csv.reader(file)
for line in csv_reader:
print(line)
        

Conclusion:

The quality code is one that is well structured, well documented, and well explained with comments. The better the quality we write, the more readability it provides and easier it becomes to remember and to understand. To keep the code consistent with PEP8, you can use various IDEs or editors. I personally use Pycharm for coding, it provides built-in linters. You may like to use Atom, VS Code, or Sublime Text, based on your preferences. All of them have plugins for inbuilt linters. If you are using any other IDE and do not have inbuilt linters you can use PyLint or PyFlakes. In my view, these IDEs can only help us to code better, your willingness to write good code still depends on you.

Recent Comments:-

There are no comments yet.

Leave message