PEP 308: ternary operator

Dan Bishop danb_83 at yahoo.com
Fri Feb 21 22:08:33 EST 2003


Terry Hancock <hancock at anansispaceworks.com> wrote in message news:<jx_4a.12853$YU4.1082191 at newsread1.prod.itd.earthlink.net>...
> (I've not been reading c.l.py for a few days, so I'm not sure which branch 
> of this thread to reply to)
> 
> I have always hated C's ternary operator syntax!  I never used it that 
> much, and every time I did I had to look up the syntax.  I REALLY hope 
> Python does not simply adopt this syntax, as I think it will go on 
> torturing newbies and casual programmers like myself if it does.  Here's 
> why it bothers me:
> 
> 1) Is it <cond>? <a>:<b> or <cond>: <a>?<b>
> I can never remember this!

It's not too hard to remember.  As someone else has already pointed
out, the question mark follows the "question" (cond).  The three parts
of the expression are also in exactly the same order as the normal
"if(<cond>) <stmt a> else <stmt b>" construct.

> Likewise, I find the current kludge of using <cond> and <a> or <b> to be 
> annoyingly idiomatic. It works by a kind of trick, and not for the reason 
> it reads well.

I agree.

> I also find the (if <cond>: <a> else <b>) syntax confusing because it looks 
> too much like the statement syntax,

Imho, that's an advantage!

> and I just can't warm up to the 
> parentheses.  I especially don't like the overloaded meanings of the 
> keywords.

But they aren't overloaded in ways that are unrelated to their old
meanings; it's still a selection construct.
 
> I therefore would like to voice support for either of the following 
> "new-keyword" options:
> 
> d = <a> when <cond> else <b>

Yuck!

> The main thing I like is that it properly places the most common action 
> (d=<a>) at the beginning where it reads nicely. Then we add the exceptional 
> case onto the end.

That's not the case in my programming style.  I tend to write
ternaries in a way that avoids inverting the condition, and half the
time the most common case is at the end, as in

isLeapYear(year) ? 366 : 365

> It has the feel of the try-except syntax in miniature.

I don't understand why that's an advantage.  If you want if-else
semantics, then why is try-except syntax better than if-else syntax?

> d = <cond> then <a> else <b>

I could live with this one, but there's just something about "then"
without "if" that doesn't feel right.




More information about the Python-list mailing list