Python Coding Standards And Best Practices For Code Quality | Zenesys Blogs

PYTHON CODING STANDARDS AND BEST PRACTICES FOR CODE QUALITY

5 min Jun 24, 2023 Ayush Kumar Sharma WEB Views : 18029
Python coding standard

Python was founded more than 30 years ago, which is long time. It’s easy to learn, even if you’re just starting out. Python is used by many people to create software, and there’s a big community of people who can help you if you have questions.

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 Python 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 Python 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, written in 2004 by Tim Peters is a collection of 19 guiding principles on which Python Development 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.

 

Features Of Pep 8 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 web development, 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 quote"
 z= 'text inside quote'
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'
elseif 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'
elseif 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.