On Readable Python Code

Standard

For more on this I refer you to the article at Live Code Stream, Make Your Code Great, Python Style which demonstrates a number of these that will elevate your code into more clean and readable code. I also refer you to the Python tutorial and the Python PEP 8 styling guide .

Naming conventions

It is advisable to stick naming conventions suggested in the PEP 8 styling guide:

Function namelower case; words separated by underscorefunction_name
Variable namesSame as function namesvar_name
Constants at module levelAll in capital; words separated by underscoreCONST_NAME

Forming Paths and Strings

I sometimes see code that forms file or directory paths and strings by concatenating them as follows:

a = "something"
b = "happened"
a  + " " + b

A better Pythonic way would be:


" ".join(a, b)

For file and directory paths I see the same approach:

directory_path = "some path to a directory"
filename = "filename"
fp = directory_path + filename

This might work on one operating system but not on other operating systems. Also this is not the right way to form a path. There are at least two appropriate ways to do so that make this OS-independent:

import os
fp = os.path.join(directory_path, filename)
# returns a string object

or my preferred method:

from pathlib import Path
fp = Path(directory_path).joinpath(filename)
# returns a Path object

Using Path allows you to perform other operations without having to write unnecessary code since pathlib provides high-level path objects:

# using os
fp = os.path.join(directory_path, filename)
os.path.exists(fp)

# using Path
fp = Path(directory_path).joinpath(filename)
fp.exists()

Tips

Tip 0: Comment your code but do not comment the obvious. Focus more on docstrings (see PEP 257) for public interfaces and making your code the documentation it self.

Tip 1: Make use of your editor to help you stick to PEP 8 and other guidelines and best practices. All popular editors are expected to have settings that allow the user to make use of these

Tip 2: Use a linter. Most editors allow you to use a linter.

Tip 2: Use black, the uncompromising code formatter, to automatically format your code as your write it.

Have you faced these before in code you worked on? What other tips or advice would you give?

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s