Update to PEP308: if-then-else expression

Evan Simpson evan at 4-am.com
Tue Feb 11 17:46:05 EST 2003


Raymond Hettinger wrote:
> * you have to look twice to see that you're dealing
>    with an expression rather than an if-statement

They behave almost identically.  If you confuse them when reading, 
what's the harm?  If you confuse them when writing, you'll get a 
SyntaxError, not a subtle bug.

> * when looking at an expression, my mind is trained
>    to see alpha characters as a variable or function name

Including 'and', 'or', 'not', 'lambda', and the various keywords used in 
list comprehensions?  (Not that I like listcomp syntax).  Isn't your 
mind trained to see familiar keywords?

> * the enclosing parenthesis requirement feels wrong

They eliminate precedence issues, make distinguishing statement from 
expression trivial, and simplify the grammar.

> * there is an unpleasant Smalltalk flavor to having
>    a single, expression operator take two keywords
>    followed by colons and parameters.  There is nothing
>    else like it in Python (it doesn't fit).

'lambda' uses a colon, and listcomps use multiple keywords inside 
delimiters.  Python doesn't have any n-ary operator for n>2, so there 
won't be anything like *any* PEP308 syntax, in that sense.

> All of these problems are solved by using punctuation
> instead of keywords:
> 
>     c ?? a || b          c ? a : b        c ? a ! b

The folks who object to PEP308 regardless of syntax have a point when 
they observe that conditional expressions seem to be very rare in 
practice.  Given that fact, if Guido agrees to add them to Python, they 
ought to be either "intuitive" or very easy to look up.

None of the punctuation forms is easy to look up, and only the one taken 
from C is likely to be immediately comprehensible to someone who isn't 
familiar with them.  If they are chained or used with complex 
expressions, you either need to add as many as *three* sets of 
parentheses, or hope that the "obvious" precedence works.

The "if C: x else: y" syntax is trivial to teach, read, and remember 
*because* it is just like an if-statement in parentheses, with 
expressions instead of statement suites.

Cheers,

Evan @ 4-am







More information about the Python-list mailing list