Does Python have a ternary conditional operator? If not, is it possible to simulate one concisely using other language constructs?
Yes, it was added in version 2.5. It's frowned upon by some pythonistas, so keep that in mind.
First For example:
Official documentation: | |||||||||||||||||||||
|
You can index into a tuple:
test needs to return True or false. It might be safer to always implement as:
| |||||||||||||||||||||
|
For versions prior to 2.5, there's the trick:
This feels more hacky than the new | |||||||||||||
|
From the documentation:
New since version 2.5. | ||||
|
expression1 if condition else expression2
| |||||||||||||
|
For Python 2.5 and newer there is a specific syntax:
In older Pythons a ternary operator is not implemented but it's possible to simulate it.
Though, there is a potential problem, which if
which can be wrapped by:
and used this way:
It is compatible with all Python versions. | |||||
|
@up: Unfortunately, the
solution doesn'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). One solution to this would be
(execution delayed until the winner is known ;)), but it introduces inconsistency between callable and non-callable objects. In addition, it doesn't solve the case when using properties. And so the story goes - choosing between 3 mentioned solutions is a trade-off between having the short-circuit feature, using at least python 2.5 (IMHO not a problem anymore) and not being prone to "trueValue-evaluates-to-false" errors. | ||||
|
You might often find
but this lead to problem when on_true == 0
where you would expect for a normal ternary operator this result
| |||||
|
Though Pythons older than 2.5 are slowly drifting to history, here is a list of old pre-2.5 ternary operator tricks: "Python Idioms", search for the text 'Conditional expression' . Wikipedia is also quite helpful Ж:-) | |||
|
protected by NullPoiиteя Jun 10 at 5:15
This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.