Conditional Expressions in Python 2.4

Python 2.5 introduced a new syntax structure: 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 a 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 expression. 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 versions of Python?

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

x = (b,a)[condition]

will yield the desired 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 a 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 want to make sure that only the function that is assigned to x is run, not both of them. In this case, the intuitive way:

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

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

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

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

Overall, the method described above offers a 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 *