Towards a more Pythonic "Ternary Operator"

Carel Fellinger carel.fellinger at chello.nl
Tue Mar 4 10:27:47 EST 2003


On Tue, Mar 04, 2003 at 01:06:02PM +0000, Clark C. Evans wrote:
> I was thinking, perhaps if people first agreed on the problem
> finding a solution could become more of a detail.  Here is a
> stab at the 'terinary operator' problem.
...
>    (a) someone reading the code has to scan the whole
>        structure and determine that there is a parallel
>        structure, where the variable is assigned a value
>        in either case of the condition; and
> 
>    (b) someone writing/editing the code has to make sure
>        that the variable is the same in both places or
>        else the parallel structure is broken.
> 
...

I think you missed

     (c) it takes up too much precious screen estate

otherwise I agree, and I think a general switch expression might
be more interesting, but as you propose the beast it only deals
with straight comparision.  What about enhancing it like:

  b = (if a <op>:
       on X: Q
       on Y: R
       else: S)

being equivalent to:

  if a <op) X:
      b = Q
  elif a <op> Y:
      b = R
  else:
      b = S

And a possible shortening syntactic sugaring could produce:

   b = (if a <opt>; on X: Q; on Y: R; else: S)

The semicolon being used to allow to put on one line what otherwise
needs two, like with multiple statements on a single line.  The parens
being required to allow nesting and making scope explicit.  And leaving
finding proper names for if (select) and on (case) for later to decide.

I think something along these lines has been proposed during the
recent ternary operator tempest, but I lost track.

Anyway, by now it looks so troublesome that I rather not have it in:)

-- 
groetjes, carel





More information about the Python-list mailing list