My Favourite Things About Python

After a year of using Python, here’s what I love most

--

Photo by Joshua Reddekopp on Unsplash

In September 2019 I started a 2 year Apprenticeship with a large UK technology company. I was practically new to Software Engineering and completely new to the Python language. However, after creating scripts for the last year, I’ve learnt so much about both. Python is definitely the language to learn as a beginner, as its simplified syntax is perfect for wading through the more complex ideas in Software Engineering.

DISCLAIMER: I’m going to share with you the things I love most about Python, however, I’m sure lots of other languages share these concepts too.

f-strings

There are loads of ways to join strings together in python, and I have used them all. For a long time I used the classic plus sign:

string = "The " + colour + " dog wanted " + food + " for dinner."

Then I advanced to using format to insert variables into strings:

string = "The {} dog wanted {} for dinner".format(colour, food)

Finally I discovered f-strings which are so much neater and more powerful than these other methods.

string = f"The {colour} dog wanted {food} for dinner."

What I love is that anything that returns a string (or can be represented as a string) can be put in the curly braces. For example a call to a method, or the returned string from the replace()or split() functions.

List Comprehension

The best way to describe list comprehension is by example:

list = []
for file in os.listdir(path):
if file.endswith(".txt"):
list.append(file.split(".txt")[0])

The above list can be created via list comprehension like this:

list = [x.split(".txt")[0] for x in os.listdir(path) if file.endswith(".txt")]

I don’t know why exactly, but using list comprehensions brings me immense pleasure and I look to use them all the time.

Writing in Prose

Python is easy to understand straight out of the box, with the lack of curly braces and simplistic syntax. Using the ‘pythonic’ way of coding increases the readability of the code. Add to these some good variable naming, and you could get away with reading your code out loud at an open mic poetry night!

if young and not wealthy:
start_saving()
if old and not wealthy:
there_is_always_the_state_pension()

(As you can tell, I’m awesome at poetry!)

OOP

I think for many people who are learning Software Engineering principals from scratch, they tend to shy away from the more complicated concepts (until they have a strong base knowledge). Certainly for me, I have only just started to embrace using classes and objects for everyday coding. I always thought that basic scripting didn’t need classes and objects and just added an unnecessary layer of complexity. But a few months ago, a colleague said to me, “even for basic scripts try creating a base class with a main function for flow of execution”. I started doing this, and over several weeks, I became more confident with the basic concepts of classes. Now, I couldn’t imagine not using OOP.

In an early script I wrote (that was actually released publicly as part of a software bundle), I used a boolean variable called passing that tracked whether any errors or warnings had been found in file it was inspecting. Multiple tests were carried out on the file and global passing was declared at the top of every function. I know this is a small thing, but it’s makes it so much cleaner to track this viaself.passing.

File Handling

I go back to the disclaimer — I’m aware other languages can do this, but when I started to open files, write to files, execute other scripts, I thought it was pure magic. One of the first tasks I was given when I started working as a developer was to write a script that opens a log file, search through the log file using regex, then output an html file to display the results in a neat table, so other engineers could easily get to the required data.

I had never thought about a script writing another executable file, but I have had to do this many times over the last year and a half, and I think it’s extremely powerful.

def tableBuilder(text, read, cost, links):
table = """
<table style="table-layout:fixed; width:900px; margin:auto; font-size:22px">
<col width=25% ><col width=20%><col width=25%><col width=30%
<tr>
<td style="border:solid 1px white">"""+ text + """</td>
<td style="border:solid 1px white">"""+ read + """</td>
<td style="border:solid 1px white">&pound;"""+cost+"""</td>
<td>
<div>
<input type="button" onclick="clickButton(this)" value="List Articles in this Period" style="width:250px; height:50px">
</input>
</div>
</td>
</tr>
</table>
<div style="display:none"><br><blockquote style="width:770px; margin:auto; padding:50px"><code>""" for i, article in enumerate(links):
table += "<A HREF={links[article]}>{i}{article}</A><br>"
table += "</code></blockquote><br></div>"
return tablehtml += tableBuilder("Current Month", str(currentMonth[0]), str(currentMonth[1]), currentMonth[2])
html += tableBuilder("Last Month", str(lastMonth[0]), str(lastMonth[1]), lastMonth[2])
html += tableBuilder("Last 6 months", str(lastSixMonths[0]), str(lastSixMonths[1]), lastSixMonths[2])

This function is an extract from a script I wrote to extract information from the medium articles I read. It slowly builds up an html string which is eventually written to file and gets uploaded to a web server. I wrote about this script in the story:

I hope you enjoyed this article, let me know if you agree with these great bits of python, or if you have any different ones.

--

--

Richard Quinn
A Journey Through My Software Development Career

“Old man changes career to become a Software Developer after 20 years in an unrelated sector”