I was under the impression that Python had a ternary operator...
But then I did some research,
Not enough to find out for sure though
Thought I'd ask the professionals ;)
I was under the impression that Python had a ternary operator...
But then I did some research,
Not enough to find out for sure though
Thought I'd ask the professionals ;)
Yes, it has been relatively recently added (in 2.5 IIRC). It's frowned upon by many pythonistas, so use with caution. The syntax is:
a if b else c
First b is evaluated, then either a or c is returned based on the truth value of b; if b evaluates to true a is returned, else c is returned.
For example:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
Official docs here.
From http://www.python.org/doc/2.5.2/ref/Booleans.html
The expression
x if C else y
first evaluates C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned. New in version 2.5.
For versions prior to 2.5, there's the trick:
test and true_value or false_value
This feels more hacky than the new A if B else C
syntax mentioned elsewhere, and is generally considered to be a Bad Thing. Although it does have the benefit of evaluating expressions left to right, which is clearer in my opinion.
You can index into a tuple:
(falseValue, trueValue)[test]
test needs to return True or false. It might be safer to always implement as:
(falseValue, trueValue)[test == True]
@up:
Unfortunately, the
(falseValue, trueValue)[test]
solution don't have short-circuit behaviour, thus both falseValue and trueValue are evaluated regardless of the condition. This could be suboptimal or even buggy (i.e. both trueValue and falseValue could be methods and have side-effects).
Some solution to this would be
(falseValue, trueValue)[test]()
(execution delayed until the winner is known ;)), but it introduces inconsistency between callable and non-callable objects. In addition, it don't solves the case when using properties.
And so the story goes - choosing between 3 mentioned solutions is trade-off between having the short-circuit feature, using at least python2.5 (2.4?) (IMHO no problem any more) and not beeing prone to "trueValue-evaluates-to-false" errors.
expression1 if condition else expression2
>>> a = 1
>>> b = 2
>>> c = 0 if a > b else 1
1
>>> c = 0 if a > b else 1 if a < b else -1
1