Open In App

Best Practices to Write Clean Python Code

Last Updated : 26 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python is one of the most loved programming languages today. Shockingly, Python has overtaken Java in the list of top programming languages and is now the most studied language! It is the second most used language after JavaScript and is slowly beating the competition to be on the top. It is used extensively across various domains like web development through popular frameworks like Django and Flask, web scraping, automation, system administration, DevOps, testing, network programming, data analysis, data science, machine learning, and artificial intelligence. In fact, the first language which comes to someone’s mind when talking about data-related technologies is Python! 

Best-Practices-to-Write-Clean-Python-Code

Along with being a heavily used language by beginners due to its ease of learning, it has huge community support and extensive documentation. But a lot of people when switching from other languages like Java, C, C++, JavaScript etcetera, find it a little difficult to follow along with the best practices that should be adopted to write clean code in Python. Clean code is easier to read and understand, debug, and elegant. So today we will be discussing all of them in detail, therefore you will get a better idea of them. So let’s get started!

Good Documentation

It is always advised to incorporate readable comments into your code. This makes the program easy to comprehend. Even a complex program can be broken down into parts and be understood because of the comments. There are two types of comments in Python:

  1. Single Line Comments: These types of comments span a single line of text. They begin with a hash symbol (#) and automatically terminate when the line ends.
  2. Multi-line Comments: They span multiple lines of text (two or more) and are ideally used when explaining a block of code. These type of comments start and end with triple quotes (”’). It is more like a text constant and can also be used to assign string to a variable. In a few cases this can cause errors therefore hash should be used for each line of comment if the comment has more than one line.

To learn more about comments, must read: Comments in Python

Clean Indentation

Unlike other languages like C++, Java etc. Python relies on space or tab indentation rather than brace specified code block. Each statement in Python is preceded by a space, double space, or tab. You cannot use a tab at one place and a space on the other as the indentation needs to be consistent throughout the code. This tells Python that you are starting a new block of code. A few examples of Python indentation are provided below:

# an example of if-else with tab indentation
if (condition 1):
    # executed when condition is True
else:
    # executed when condition is False
# an example of for loop with nested if-else and double space indentation
for i in sequence:
  if (condition 1):
    # execute outer if block code
    if (condition 2):
      # execute nested if code
  else:
      # execute outer else block code

To learn more about indentation, must read: Indentation in Python

Using Virtual Environments

Virtual environments in Python are a type of sandbox area for a project. In this environment, whatever libraries and packages you will install will be clearly isolated from the ones installed outside the environment, say the operating system or other virtual environments. You can have multiple virtual environments at a point in time, and it is recommended to use these environments every time you are working on a different or new project. This facilitates separating dependencies and helps to share code easily. Next time anyone wants to run your software, rather than making them install libraries one by one, you can send the requirements file (containing all installed packages and libraries for that specific project). This can be done using the freeze command as follows:

pip freeze > requirements.txt

This command lists all your installed packages and outputs those into the requirements.txt text file. Next time someone installs it, they can run the following command:

pip install -r requirements.txt

Which installs the dependencies recursively without manually typing them one by one to install.

To learn more about virtual environments, must read: Virtual Environments in Python

Modular Code

Python developers strictly follow the DRY principle, which states Don’t Repeat Yourself. This means if you want to accomplish a task multiple times, rather than writing redundant code. This not only means writing functions to carry out repetitive tasks but rather making modules. Modules are more like a code library, typically a file that contains code you want to implement in your Python program. The Python community is huge and a lot of developers have implemented modules that involve code that is frequently used. You can make your own module that performs a specific task! So rather than reinventing the wheel and writing the code from scratch, you can simply import the module and use its functionality. This is done by using the import keyword:

# importing regular expression package
import re

# using it in your code
regex = re.compile(r'pattern')

# importing tensorflow with an alias that makes
# the usage concise
import tensorflow as tf

To read more about modules, visit: Modules in Python

Meaningful Variable and Function Names

Python language follows the snake case when it comes to naming variables and functions. So a variable that is named FooBar in any other language that follows camel case naming convention, is named as foo_bar in Python. Python will not throw an error if you use camel cases or flatcase, but it is not desired. Along with variable names, function names in python also follow snake case naming convention.

“Pythonic” Code

There are a lot of unique ways to implement a specific task in Python. These are concise methods that help in shortening the code and make it look elegant. Let’s look at each of them one by one.

  1. List Comprehensions: It is a sophisticated way to create lists in a single line. Rather than explicitly using assignment inside a loop, we can create a list within square brackets with the loop defined inside. To read more about list comprehensions, must read: List Comprehensions in Python.
  2. Swapping Variables: When swapping variables in python, rather than using temporary variables and other weird ways (adding or dividing variables) you can do it in a single line of code. Example, to swap two variables, a and b: a, b = b, a. This is Python’s way of swapping variables!
  3. Slicing: It is used to carve out a specific part of a list or a string. It is super useful when you need to extract a smaller list or string from a larger one and can be implemented using a colon as a separator in between the initial and the final variables. You can even leave the start or the end value. To read more about slicing, must read: Slicing in Python.

We have discussed most of the ways that you can adopt in your Python code to make it look elegant and crisp. These also help to debug your code easily and make it more readable. 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads