Choosing a ternary operator for Python
[Posted March 13, 2003 by corbet]
C and C++ programmers encounter the ternary operator early in their
education. This operator, which in C syntax, looks like:
<condition> ? <expression1> : <expression2>
evaluates to expression1 if (and only if) the given
condition evaluates true; otherwise expression2 is
chosen. The ternary operator is a compact representation of a common
operation (choosing between two values), and it is a heavily-used feature
in languages which provide it.
Python does not provide a ternary operator, much to the chagrin a subset of
hackers who are otherwise very happy with the language. As a way of
responding to years of requests, Python Benevolent Dictator For Life Guido
van Rossum posted a proposal for a Pythonic
ternary operator, and asked the community to get back to him with its
opinion. To say that the discussion was active would be a substantial
understatement; thousands of messages were posted discussing the merits of
ternary operators, whether Python should have one, and what form it should
take. The result was a revised version of PEP 308.
That proposal included a few possible forms for a Python ternary operator.
The primary proposal was for this form:
(if <cond>: <expr1> else: <expr2>)
This form is easily extended to four or more operands:
(if <cond>: <expr1> elif <cond2>: <expr2> else: <expr3>)
Unusually for Python, the parentheses would be mandatory. For that reason,
and the fact that the syntax looks a lot like the regular
if/else control structure, not everybody was happy with this
proposal. So a number of alternatives were floated as well. They range
from the standard C syntax to variants like:
<cond> and <expr1> else <expr2>
<cond> then <expr1> else <expr2>
<expr1> if <cond> else <expr2>
cond(<cond>, <expr1>, <expr2>)
<cond> ?? <expr1> || <expr2>
<cond> -> <expr1> else <expr2>
If this were Perl, the language hackers would have probably just
implemented all the possibilities and been done with it. But Python
programmers like
to have one accepted way of doing things, so a decision had to be made. A
vote was held, and the results are now
available.
No alternative won a clear majority of the 518 votes counted. The
parenthesized syntax from the proposal got the most votes, but the C syntax
was not far behind. The "no change" contingent was rather smaller, but
very passionate in its arguments. The end result is that vote coordinator
Raymond Hettinger has not chosen to certify a winning proposal as such.
Instead. he is passing the results back to the Benevolent Dictator who,
after all, has a rather larger vote than anybody else. As of this writing,
Guido has not made his decision known.
(
Log in to post comments)