PEP 308: Alternative conditional operator forms
Robin Munn
rmunn at pobox.com
Mon Feb 10 16:42:55 EST 2003
Sean Ross <sross at connectmail.carleton.ca> wrote:
>
> "Erik Max Francis" <max at alcyone.com> wrote in message
> news:3E46F0CE.5675E180 at alcyone.com...
> C -> (x, y)
>>
>> What else should be on this list? (You can reply by email if you wish.)
>>
>
> [x if C else y]
>
> (proposed by Alex Martelli, in a previous post)
Almost, but not *quite*, what I wanted to suggest. I propose:
(x if C else y) # Parentheses are *required*
This is identical to the format proposed in PEP 308 with the exception
that parentheses are required around the ternary expression.
Rationale:
* It is reminiscent of list-comprehension syntax. Alex Martelli's
suggestion is even more so, of course, but I think it has the
potential to cause confusion. We have [x for x in l] syntax for list
comprehensions, something similar using {} for dictionary
comprehensions. What's left? Parentheses.
* The syntax is virtually the *same* as that proposed in PEP 308, which
I consider to be pretty Pythonic: it's easily understood in one
reading and pretty much unambiguous.
* This syntax is even more easy to read (IMHO) than the PEP 308 syntax;
the required parentheses automatically mark it off as a single
expression.
If this is adopted, the question then arises of what do with statements
like the following:
x1 if C1 else x2 if C2 else x3 if C3 else xdefault
Two possibilities exist:
(x1 if C1 else (x2 if C2 else (x3 if C3 else default)))
or:
(x1 if C1 else x2 if C2 else x3 if C3 else default)
The first is a natural extension of the required-parentheses rule, but
the second reads more like a single switch-like construction.
Even if this proposal is not accepted but PEP 308 is, I will still write
all my ternary-conditionals with parentheses around them; I believe that
good style will demand it.
--
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838
More information about the Python-list
mailing list