Last night we ran into a slight problem. We are running Python 2.5 on our Macbook’s, but our server is running a very stable 2.4. No problem right? Well kind of.
The first problem we encountered is related to PEP 308. Someone who had written a RSS parsing plugin for Django, failed to mention that it minimally needed Python 2.5 to run correctly. But this is one of the greatest advantages of open source. I rolled up my sleeves and removed what the PEP calls conditional expressions. I’ve always referred to these as the Ternary operator [or operation].
I must admit, the style used in Python is nothing like I’ve ever used in C/C++, etc. An example of what I had to replace was:
author = entry.author if entry.has_key('author') else ''
if entry.has_key('author'): author = entry.author else: author = ''
You can see how much simpler it is to write the first one. It may be harder to read at first, but if you think of it as:
x = true_value if condition else false_value
Here is the original code I fixed to make it work with Python 2.4. There are some other shortcuts going on. One for example may be a bit more confusing at first, but it is nothing more than a “short cut” to make things simpler to write and read, right?!? 🙂
Take a list:
>>> a = range(0,10) >>> print a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Now suppose I want a list where I multiply every value in this list by 2. I could write:
>>> x =  >>> for number in a: >>> x.append(number*2) >>> print x [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
To make the iteration more simple, Python allows us to comprehend the list into:
>>> x = [number * 2 for number in a] >>> print x [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
This is best expressed as:
L = [expression for variable in sequence]
You can find out more about Python’s list comprehension here.
When rewriting the code, because I was unable to use PEP 308, I decided to write a classic iteration loop, to make the code a bit simpler to read and understand. There is no reason to wrap a comprehensive list over multiple lines just because you can. 😉