Sitemap

Python Pet Peeves

2 min readApr 18, 2017

--

I have decided to blog about various python code snippets, I see online and elsewhere.

1. try/except blocks.

try:
major = version.rsplit(“.”)[0]
except IndexError:
major = “0”
# The minor version
try:
minor = version.rsplit(“.”)[1]
except IndexError:
minor = “0”
#The release version
try:
release = version.rsplit(“.”)[2]
except IndexError:
release = “0”
#The patch version
try:
patch = version.rsplit(“.”)[3]
except IndexError:
patch = “0”

Basically a total abuse of try/except blocks. It ll miserably fail for strings “a.b.c.” without raising index errors. I am not a huge fan of try/except blocks unless you really really really need it. Of course, you cannot cover all the cases and surrounding yourself with the bastion of try/except makes me feel comfortable. But more often, forcing your mind to not use one, helps me come with better code.

Get Rahul Ram’s stories in your inbox

Join Medium for free to get updates from this writer.

One of the ways, I was thinking was to get a list of size 4 which should default to “0” if no value exist. No matter what size is version string. I should be able to extract only 4 values based on the split and get the associated version numbers. I finally came up with the following,

version_list = map(lambda x,y: x if x and y!= None else “0”, version.split(“.”)[:4],xrange(4))

I am basically apply the lambda function on 2 lists. The xrange function ensures that, I process atleast 4 indices. so if version = 5.6. (mind the extra . in the end :) I ll still have version_list = ["5”,"6","0","0"]

This way, I totally prevent using the try/except block and code is much leaner. Ofcourse, there are other alternatives. I ll keep adding as and when I get time to add more.

--

--

Rahul Ram
Rahul Ram

Written by Rahul Ram

@Distributed Systems @StreamingData @Coffee