PEP 308: ternary operator

Terry Hancock hancock at
Sat Feb 22 08:40:19 CET 2003

Dan Bishop wrote:
> 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.

I was just trying to point out that it was not really intuitive.

The fact that you need to explain it, is evidence enough to me, and I 
figure that if it has confused me before, that it will confuse others.

>> I therefore would like to voice support for either of the following
>> "new-keyword" options:
>> d = <a> when <cond> else <b>
> Yuck!

Expressive,  but unhelpful towards understanding *why* you don't like it. 

I like "when" for several reasons. Not least is that when some unsuspecting 
newbie hits this in my code, they will immediately know this is a new 
construct, and be able to look it up under "when" where they will get 
correct information.

But the most obvious reason is that it reads as fairly correct English:

d = a when c else b
Set d to a when c, else [set it to] b.

d == a when c else b
Compare d to a when c, else [compare it to] b.

Even the elision of the second verb clause is fairly common in spoken 

That would work if you substitute "if" for "when", but it wouldn't be as 
easy to look up, nor as distinct.  Still, I'd be okay with it.

But consider how mangled this is:

Set d to if c then a else [set it to] b.

"Set d to if"?

>> 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.

Which is why I like "when" better.

It also has the same problem with seeming to assign d to something 
non-sensical.  Well, actually to a boolean value in this case.

But the main thing I was trying to say is that I don't like the 
symbol-based syntaxes.  To me, they really feel out of place in Python. 
That's true of the C-based syntax, but also of the other symbol syntaxes.

But I'm all for including the operator concept itself.


Anansi Spaceworks

More information about the Python-list mailing list