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

Erik Max Francis max at alcyone.com
Mon Feb 10 00:30:54 EST 2003


Andrew Koenig wrote:

> Why is extra lookahead required here?  The "if" is the first token in
> the statement, so it can only denote an if-statement, not an
> if-expression.  Then we look at the grammar, which says that
> an if-statement in this case is
> 
>         "if" expression ":" suite "else" ":" suite
> 
> and we see that a suite must end in a newline.

Right.  I'm just saying saying that if you want a conditional expression
to be legal as a standalone statement, that requires a parser change in
how if statements are handled -- i.e., you have to look ahead and see
"oh, there's an `else:' on this same line, so this is the conditional
operator as a standalone statement, not an if statement.  But ...

> If you parenthesize it:
> 
>         (if debug: sys.stderr.write('got here\n') else: None)
> 
> then the "if" is no longer the first token in the statement, so it
> introduces an if-expression.  No problem.

Right, and that was my suggestion somewhere in the thread (and via
email).  The corner case (which I shall hereafter refer to as The Corner
Case :-) -- where the conditional expression is written as a standalone
statement -- is not important to me, so I have no problem disallowing
it; that means no parser changes are necessary (as far as I can tell)
other than the introduction of the conditional expression (which is an
expression and thus does not interfere with the if statement parsing.

The only thing I might say about my disinterest in the Corner Case is
that it might be nice that if you think you're parsing an if statement
and see an `else:' on the same line, a slightly more helpful SyntaxError
is emitted (i.e., "Hey, you can't do that; use parentheses or put the
else on a separate line").  But that's optional.

I don't forsee myself using the Corner Case in real code, nor do I see
it becoming particularly popular, so I'm rather ambivalent to its
resolution.

I must say I'm pretty convinced at this point that `if C: x else: y'
(and if we wish, its multiway variants `if C: x elif D: y else: z') is
absolutely the way to go if you want a conditional operator.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ She glanced at her watch ... It was 9:23.
\__/ James Clavell
    Bosskey.net: Quake III Arena / http://www.bosskey.net/q3a/
 A personal guide to Quake III Arena.




More information about the Python-list mailing list