For review: PEP 308 - If-then-else expression
Andrew Koenig
ark at research.att.com
Sun Feb 9 23:42:36 EST 2003
Erik> Well, it's unambiguous, but it could require some extra
Erik> lookahead. I'm no Python parser expert, but it seems to me the
Erik> only case this happens is when the conditional expression is
Erik> used as a standalone statement, e.g.
Erik> if debug: sys.stderr.write('got here\n') else: None
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.
This example is therefore a syntax error; one way to rewrite it is:
if debug: sys.stderr.write('got here\n')
else: None
Erik> which I must admit is a little perverse in and of itself,
Erik> particularly as an example -- but Guido used it in the PEP so I
Erik> will use it here too. (No saying, "Duh, just remove the "else:
Erik> None"; I know that perfectly well, and so did Guido.) I would
Erik> have no problem with, say, requiring parentheses in this one
Erik> case; in all other cases, if you're expecting an expression and
Erik> you see an `if', you know what's up. (Right?)
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.
And no lookahead required. All that's needed is to check whether
the "if" is the first token of its statement.
>> And i'd probably think that
>> if if y<5: yep() else: 0:
>> is the result of some editor-accident :-)
On the other hand, if you drop one of the "if" tokens:
if y<5: yep() else: 0:
it's a syntax error, and it's still a syntax error if you drop the :
at the end:
if y<5: yep() else: 0
Erik> But that's true with any form of a conditional operator as the
Erik> conditional expression of an if statement (and quite frankly, in
Erik> any language that has both an if statement and a conditional
Erik> operator); that's just obtuse. The only thing that makes it
Erik> look like a stutter here is the fact that you see two `ifs' in a
Erik> row, which I think would be almost a benefit for the jackass who
Erik> wrote this code -- right away you know someone did something
Erik> weird instead of having to wade through it.
Hear, hear!
--
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark
More information about the Python-list
mailing list