5 Best Python Practices To Remarkably Improve Code Quality

Stop importing all using import *

To start using Python for variety of analytics, automation tasks we need to import functions and classes from a Python package.

One of the most common practice beginners follow is importing everything from the package using import * .

🚩 The import * statement imports all the functions and classes which may clash with the functions you define or functions of other libraries that you import. So there will be always a risk of function overriding or variable overriding.

🚩 Plus, when you use import *, it is difficult to recognize what is imported from which particular library and thus reduces code readability.

Therefore a good practice is to import only required methods/functions from a package such as import function_name from package_name . ✔️

For example, importing function Counter from collections library

from collections import Counter

Well, if you still want to import all the functions from a package, you can do it without saying import * . A classic example of this use-case is importing everything from pandas for data analytics.

❌ Bad practice: from pandas import *

✔️ ️Good practice: import pandas as pd

And then you can use all the functions from pandas package with prefix pd. for example, pd.DataFrame()

Specify the exception in the Try-Except

Just like every beginner, I used to have this bad habit of not mentioning exception in the except clause of try-except statement.

for example, not mentioning any exception in the except clause does not give us any idea about what has been happened exactly when except clause is executed.

No exception in except | Image by Author

Ideally, there should be some error in a or b but not mentioning exception in the except clause gives us no idea about what is happening.

Also without mentioning exception, we can not catch a specific error in the code and thus weak control over the flow of the code.

This can be converted into good practice by mentioning the exception as below.

Exception in except clause | Image by Author

Handling the NameError in the except clause gives us exact reason for non-execution of try clause. ✔️

You can find all the exceptions in Python here and details about how to use try-except can be found here.

Use Dictionary methods

You might know the dictionary methods .keys(), .values() and .items() to access only keys, values and key-value pairs respectively.

In case you don’t know, here is a quick example.

# Create a dictionary with,
# keys 'A', 'B', 'C', 'D'
# values 1001, 2002, 3003, 4004 respectively
mydict = {'A': 1001,
'B': 2002,
'C': 3003,
'D': 4004}

Extract keys, values and key-value pairs from Python Dictionary | Image by Author

As seen in the above picture, the key — value pair as tuple, can be extracted with .items().

However, sometimes it is not used correctly. for example, for displaying keys and values from the dictionary using for loop, some coders write,

mydict.keys() | Image by Author

In the above scenario, mydict.keys() in the for loop is unnecessary and mydict[keys] in the print statement is less efficient. 🚩

Instead we can use mydict.items() which is more efficient as shown below.

mydict.items() | Image by Author

In this way, we can always unpack keys and values from key-value tuples generated by .items() method. ✔️

If you are willing to learn more about dictionaries in Python, here is a quick read.

Python Dictionary: 10 Practical Methods You Need to Know

..Learn how to Master Python Dictionary in under 5 minutes!

pub.towardsai.net

Use zip() to iterate over multiple lists

One of the common bad practice I noticed and even followed when I was beginner was using a index to iterate over multiple iterables such as lists, dictionaries.

❌ Bad practice look like,

Iterate through lists | Image by Author

See, this is not completely wrong as it generates output we want. However, it is not efficient and good practice.

Instead, use more readable zip() function. By definition, the zip() function in python is used to aggregate elements from multiple iterable objects element-wise into an iterable of tuples. ✔️

This property of zip() function can be used in for loop to iterate over multiple iterables (lists or dictionaries) in Python.

Iterate over multiple lists in parallel | Image by Author

Simple it is!

Open a file using “with”

A file which is opened must be closed immediately after job is done — is the best practice.

I, like million others, was using open, close, read, write to work with the files like below,

f = open('new_file.txt', 'w')
f.write('This is first line')
f.close()

The problem with this is, the last line f.close() is mostly forgotten! 🚩

And then if the write/read methods throw an exception, the file won’t be closed.

The best alternative here is to use with to open and edit the file, as shown below.

with open('new_file.txt', 'w') as f:
f.write('This is first line')

In this way, you don’t need to close the file exclusively. Once you write new line of code, outside with statement’s indent, the file gets closed automatically. ✔️

I hope you finished this article quickly and found it useful.

When these best practices are adopted, it can save a huge time wasted in debugging and understanding the code in future. 💯

I am using Python since past 4+ years and still learning good practices to improve my code quality. 💪

Interested in reading unlimited stories on Medium??

💡 Consider Becoming a Medium Member to access unlimited stories on medium and daily interesting Medium digest. I will get a small portion of your fee and No additional cost to you.

💡 Don’t forget to Sign-up to my Email list to receive a first copy of my articles.

Thank you for reading!