As network automation/DevOps engineers, we often tend to overlook the way we write a script. The focus is always on providing accurate results, which is great, but as we scale our script or application, a focus on the readability of the script is essential.
This becomes a key requirement when we start to work as a team where we have multiple contributors for a script or set of scripts.
Let's look at an example of a bad Python script that returns the result as expected (output is correct):
x=input("What is your name:")
print ("how are you"+x)
y="how are you"+x
if ("test1" in y) and ("test2" in y):
print ("cool")
x=y.split(" ")
x=x[2]+"awesome"
if ("are" in x):
print ("not cool")
After the second or third line of code as we read through, we lose the understanding of program flow, and what the expected result was. Eventually, it becomes very difficult to interpret even a simple script such as this.
Imagine how difficult it would be for someone who has not written this code to interpret a bigger script (say, 50 lines).
Now, let's modify this code to make it readable:
#ask for input of user's name and prints it with a message
x=input("What is your name:")
print ("how are you"+x)
y="how are you"+x
#validates and prints message if 'test1' AND 'test2' exists in input
if ("test1" in y) and ("test2" in y):
print ("cool")
#splits the sentence stored in variable x with blank spaces
x=y.split(" ")
print (x)
#adds the string "awesome" to the third word in the sentence and stores it in x
x=x[2]+"awesome"
#validates if word "are" is in x and prints the message accordingly
if ("are" in x):
print ("not cool")
As we can see, each section (or line) that achieves a specific result is tagged by a remark line (denoted by #). This line is a human-readable line that is ignored by the program (or compiler) and is used to ensure any reader of the program understands what is going on in each section. This ensures that each and every aspect of the script is easily understood by the reader; as the script is enhanced, troubleshooting and modifications in the program become very easy.
Another key aspect in the readability of a program is to ensure we add some key information at the very start of the code.
A generic suggestion would be to include the following:
- The author's name
- Version of the script (starts with 1.0)
- One-liner description of basic usage of the script
- Any specific installation requirements
As an example, let 's add this to the very top of the preceding script:
#Name: Abhishek Ratan
#Version: 1.0
#Usage: Asks for user input and validates it for some specific keywords
#Additional installation required: None