20090116

Ternary operator in Python

People coming from C-style languages such as PHP and C++ often wonder why there is no ternary operator (the weird x ? y : z construct) in Python.


This operator is usually used in assigments, for example


someval = (condition() ? value1 : value2);


Where someval's value depends on the return value of the function named condition(). If condition returns a value that evaluates to true, then someval will be set to value1, if false then value2.


The fact is that there is a way in Python that lets you use this kind of assignments. The trick is to use the conditional operators.


Here's an example:


>>> condition = True
>>> x = condition and 'is true' or 'is false'
>>> print 'condition %s' % x
condition is true
>>> condition = False
>>> x = condition and 'is true' or 'is false'
>>> print 'condition %s' % x
condition is false


The rule that enables this is that the return value of a logical operation (if true) is always the last value. This guarantees that x will always get a value.


Of course in C-style languages there are things one can do with the ternary operator that would fail in Python, but with logical operators the most typical use of it can be simulated, and it's even a bit more readable for people who are not very familiar with the language. I would even go as far as saying it's syntax is superior to the ? : notation.

No comments:

Post a Comment