Conditional Expressions in Python 2.4

Python 2.5 introduced new syntax structure: the conditional expressions. For programmers in languages such as C these structures seem very basic and fundamental but Python lacked them for many years. As I said Python 2.5 introduced such syntax structure, one may use it in the following form:

x =  a if condition else b

As you probably guessed a is assigned to x if condition evaluates to true and b is assigned otherwise. This is pretty much equivalent to the C conditional expressions. But as I said, this structure was only introduced in 2.5. Previous versions of Python are still widely deployed and in use, so how do you achieve the same thing in older version of Python?

To create a conditional expression in earlier versions of Python, we can utilize the tuple for the values and the tuple’s index for the condition. For example:

x = (b,a)[condition]

will yield the wanted result. x will be assigned a if condition is true and b otherwise. It works because Python treats the condition inside the index as 1 if condition is true, and as 0 if false.

This method provides very nice and clean alternative to the conditional expressions available in Python 2.5. However it does require some special attention in some cases.

Let’s say we want to assign x the value of f() if condition is true, and the value of g() otherwise. But we won’t to make sure that only the function that is assigned to x is ran, not both of them. In this case the intuitive way:

x = (g(),f())[condition]

will not be any good, because Python will generate first the tuple, and to so evaluate both f() and g(). To prevent it we will need to change a bit the order of things. Consider the following snippet:

x = ((g,f)[condition])()

It will do what we wanted because the conditional expression gives back the function itself first, so neither f() nor g() are evaluated. After the conditional expression returned then the selected function is called. While this method works it has some drawbacks. For example if f and g would require arguments, and this arguments would be different for each function, the above method couldn’t be utilized. However this is only a small drawback, and under this circumstances one can just go for regular if..else structure.

Overall the method described above, offers clean and simple alternative to the built in conditional expressions in Python 2.5, which is also compatible with previous versions.

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.