For review: PEP 308 - If-then-else expression

Jamie Guinan guinan at bluebutton.com
Sun Feb 9 00:42:40 EST 2003


This is my second direct response to PEP 308.  In my first response
I stupidly missed the fact that these are *expressions* we're talking
about, so the classic.

   if expr:
      ...
   else:
      ...

isn't a valid point of comparison since "if" doesn't return a value.
I'm new here, and I thank those who replied to me for being gentle.

Now, having read most of the replies in this enormous thread (well over 
100 now), there were a good number of proposed alternatives, each of which
had its +'s and -'s.  I'm going to add one more to the pot. Namely, a 
multi-line "case" expression.

Guido:

  <expression1> if <condition> else <expression2>

Me:

   case:
      <condition>:
          <expression1>
      1:
          <expression2>

This is not a control-flow construct; you can only put one 
expression per condition.  Notice that it's about the same
amount of typing (excluding whitespace) as Guido's.

To me, it is in keeping with the "classic" feel of Python (consistent
look-and-feel, indentation preceded by ":"), rather than opening 
the door to squeezing impossibly complicated expressions onto a single line.

Generally, the syntax (including result) would be:

   <result> = case:
       <cond1>:
           <expr1>
        <cond2>:
           <expr1>
        ...
        <condN>:
           <exprN>

If it falls of the end, the result is None.

+ There is no need for a "default" keyword, just use "1" (or True).  
+ You only have to refer to <result> once.
+ <cond>'s are evaluated one-by-one, so short-circuiting works.a
+ No "else", comma's, or brackets required.
+ Nestable without losing clarity.

- It adds an extra keyword "case".  ("default" isn't
  required, just use "1" (or True these days))


-Jamie

p.s.

The bike shed should be green. Emerald green. With yellow stripes.




More information about the Python-list mailing list