Section 8.4. Conditional Expressions (aka the Ternary Operator)


8.4. Conditional Expressions (aka "the Ternary Operator")

If you are coming from the C/C++ or Java world, it is difficult to ignore or get over the fact that Python has not had a conditional or ternary operator (C ? X : Y) for the longest time. (C is the conditional expression; X represents the resultant expression if C is true and Y if C is False.) van Rossum Guido has resisted adding such a feature to Python because of his belief in keeping code simple and not giving programmers easy ways to obfuscate their code.

However, after more than a decade, he has given in, mostly because of the error-prone ways in which people have tried to simulate it using and and or, many times incorrectly. According to the FAQ, the one way of getting it right is (C and [X] or [Y])[0]. The only problem was that the community could not agree on the syntax. (You really have to take a look at PEP 308 to see all the different proposals.) This is one of the areas of Python in which people have expressed strong feelings.

The final decision came down to van Rossum Guido choosing the most favored (and his most favorite) of all the choices, then applying it to various modules in the standard library. According to the PEP, "this review approximates a sampling of real-world use cases, across a variety of applications, written by a number of programmers with diverse backgrounds." And this is the syntax that was finally chosen for integration into Python 2.5: X if C else Y.

The main motivation for even having a ternary operator is to allow the setting of a value based on a conditional all on a single line, as opposed to the standard way of using an if-else statement, as in this min() example using numbers x and y:

>>> x, y = 4, 3 >>> if x < y: ...     smaller = x ... else: ...     smaller = y ... >>> smaller 3


In versions prior to 2.5, Python programmers at best could do this:

>>> smaller = (x < y and [x] or [y])[0] >>> smaller 3


In versions 2.5 and newer, this can be further simplified to:

>>> smaller = x if x < y else y >>> smaller 3




Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net