[Python-Dev] Trinary Operators

Gary Herron gherron@islandtraining.com
Thu, 6 Feb 2003 15:46:51 -0800


On Thursday 06 February 2003 11:49 am, Guido van Rossum wrote:
> > If this is just for fun, why stop with just "trinary"?
>
> (Which BTW is a non-word; the correct term is "ternary".)
>
> > How about one of the following (depending on ease of parsing)?
> > These look even more like list comprehension.
> >
> >   x = (e1 if c1        e2 if c2        e3 if c3  ...  else d)
>
> Doesn't parse.  The concatenation of two expressions is not
> always distinguishable from a single expression: consider c1 = f and
> c2 = (1, 2).
>
> >   x = (e1 if c1  else  e2 if c2  else  e3 if c3  ...  else d)
>
> That works.

Now that I've had a little more time to thing about it, this
suggestion of a n-ary form is nothing more than nested ternary forms
with extra parentheses removed:

 (a1 if c1 else (a2 if c2 else b2))

could be allowed to be written as

  (a1 if c1   else  a2 if c2   else  b2)

and, if you want:

  (a1 if c1 else 
   a2 if c2 else 
   b2)


Other sub-threads of this thread are discussing how to parse these
ternary operators if the parentheses are not required.  I think the
parentheses *should* be required (see below for why) and so it would
be nice to allow this extended form and not require the inner set of
parentheses when doing "tail nesting" (to invent a term).

BEWARE:  UNPYTHONIC UGLINESS FOLLOWS!

On the other hand, if the parentheses are NOT required, we get a whole
host of *UGLY*, absolutely unreadable, nesting possibilities:

  a if b else c if d else e  <==>  (a if b else c) if d else e

and even worse

  a if b if c else d else e  <==>  a if (b if c else d) else e

And what about statements

  if a if b else c if d else e:
    f
  elif g if h if i else j else k:
    l
  else:
    m

Of course, any feature can be abused, but this seems *too* abusable.

Gary Herron