How to write cleaner and more readable (python) code
3 min read

How to write cleaner and more readable (python) code

How to write cleaner and more readable (python) code

Intro

If you wish to consistently improve your programming skills, subscribe to my newsletter, it keeps you updated with the most recent programming tips and projects.

In this article, I'll explain how to write clean(er) python code, although most of those tips can be used for any language. But before getting into the main topic, this easter egg summarizes this article pretty well:

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Structure your code correctly

Use proper spacing

Unlike other programming languages, spacing in python is pretty important and therefore somewhat more strict. That doesn't mean you don't have some freedom: and in this case, spacing means the space between lines. Try to separate each function with one or two blank lines, and each chunk of code as well. You can even add more lines between parts of the code that are not related. For example, instead of writing:

from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
	return render_template("index.html")
@app.route("/page2.html")
def pg2():
    return render_template("page2.html")
if __name__ == "__main__":
	app.run(host='0.0.0.0', debug=True, port=3134)

Write:

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():
	return render_template("index.html")
    
@app.route("/page2.html")
def pg2():
    return render_template("page2.html")
    
    
if __name__ == "__main__":
	app.run(host='0.0.0.0', debug=True, port=3134)

Okay, this might be obvious, but don't forget about it!

Your code should have an order

First, import all your libraries. Then, create your variables and your constants. After that, create your classes and your functions. Only then, use all of these existing objects to accomplish whatever you want to do. If you want to write even better code, run everything in a main() function that you can call using the if __name__ == “__main__” statement. Here is what such a structure might look like:

import library1
import library2


X_SIZE = 700
Y_SIZE = 400
COLOR1 = (0, 0, 0)
COLOR2 = (255, 255, 0)
COLOR3 = (0, 255, 127)


variable1 = 0
variable2 = True


def function1(...):
	...
	
def function 2(...):
	...
	

def main():
	#use everything in here
	

if __name__ == “__main__”:
	main()

On a side note, constants are usually written in all caps and with underscores, while variables are written in lowercase.

Document your code correctly

Your variable should speak for itself

Don't name your variable something like x, var1, or thing. Instead, name it according to what it contains, for example winHeightX, n_attemps, message, etc...
On top of that, did you know you can specify the type of the variable in python, using a colon:

int_variable: int = 10
text: str = "hello!"

Using a silly example, what gives more context to the reader of your code?

x = 11800000

or

ohio_population: int = 11800000

#you can even you underscore to make your integers more readable
ohio_population: int = 11_800_000
.

Comment your code

This one speaks for itself, but don't neglect it. You don't write comments just for other people to read your code, but also for yourself when coming back to a piece of code a few days after touching it (believe me, it's a lifesaver).

Use the name of your imported library

What I mean by this is, don't use:

from library import *

but instead:

import library
#or
import library as lib

This should be common practice, you want to know where your variables and functions come from. On top of that, python developers adopted "standard" naming for some libraries, so using them as well will automatically make your code more understandable. For example:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Bonus: don't make one function do everything

This is my last little tip: use multiple smaller functions instead of one big function that does everything. Your code should be built block by block. Furthermore, by naming and commenting each function properly, your code will be even more understandable and you will have an easier time implementing it!

Thanks a lot for reading! and I hope that you will implement the methods described here so that one day, every piece of python code in the world will be as clear as ice. In the meantime, subscribe to my newsletter to get notified of all my new and upcoming tips!