[Python-Dev] Adding C ternary select (a?b:c) to Python?

Greg Ward gward@cnri.reston.va.us
Mon, 31 Jan 2000 09:15:08 -0500


On 30 January 2000, Ka-Ping Yee said:
> On Sun, 30 Jan 2000, Tim Peters wrote:
> > If this goes in (I'm not deadly opposed, just more opposed than in favor),
> > I'd like to see "else" used instead of the colon (cond "?" true "else"
> > false).  The question mark is reasonably mnemonic, but a colon makes no
> > sense here.
> 
> I agree with that sentiment (along the lines of the philosophy that
> chose "and" over "&&"), and it seems to me that it makes the most sense
> to use words for both:
> 
>     a = x > 0 then x else -x

Yeah, I agree with Tim: it's a handy feature and I frequently wish I
could do simple conditional assignment without resorting to a full-blown
if/else.  (I think I stumbled across "a and b or c" myself -- either
that or it was suggested by *Learning Python*, but lay dormant in my
subconscious for several months -- which means that I missed the "b must
always be true" subtlety until it bit me.  Ouch.  I avoid that idiom
now.)

BUT the C line-noise syntax is not appropriate.  It's fine in C, and
it's eminently appropriate in Perl -- both languages designed to
minimise wear-and-tear of programmers' keyboards.  But keyboards are
cheap nowadays, so perhaps we can be a bit more profligate with them.

I find Ping's proposed syntax intriguing.  Personally, I've always been
partial to the

    x = if a then b else c

syntax, even though I don't think I've ever used a language that
includes it.  (Oh wait, the toy ALGOL-knockoff that we used in Intro to
Compilers had it, so I *have* written a parser and simplistic code
generator for a language that includes it.  Perhaps that's why I like
it...)

But either of these -- ie. elevate "then" to keywordhood, with or
without "if", and no colons to be seen -- smell like they would play
havoc with Python's grammar.  And they turn a statement keyword "if"
into an expression keyword.  Not being at all familiar with Python's
parser, I should just shut up now, but it feels tricky.

And of course, any proposed syntax changes nowadays have to take JPython
into account.

        Greg