New - Conditional expressions in Python 2.5
Archive - Originally posted on "The Horse's Mouth" - 2006-07-01 07:39:27 - Graham EllisPython has always been described as a "tight" language in that new syntaxes are only added with a great deal of thought, and then only if they provide a significant benefit without diluting the crispness of the language.
There have been long discussions in the Python world about adding in a conditional operator - something that gives and easier form to an if / else construct that's used only to set a variable to one of two alternative values. Now, in release 2.5 which went out to Beta release in the last few days, such a facility has been added.
Suppose you have a variable called stock_level and you want to set up another variable (for output) with the word "is" or "are" in it, depending on whether the stock level is 1 or something else, you can write (as from Python 2.5):
word = "is" if stock_level == 1 else "are"
which is much shorter that the alternative so far available:
if stock_level == 1:
word = "is"
else:
word = "are"
For anyone with a Perl, PHP, C or Java backgrond, this new syntax is the moral equivalent of the ? : operator. After long discussion, Guido van Rossum decided for the syntax shown above ... amongst the reasons for this surprising choice are the fact that the ":" character is already very significant in Python and although the syntax rules would have allowed Python to follow the other languages, resultant code would not have been clear and easy to follow.