PEP 308: Alternative conditional operator forms -- Corner Case solved
pedronis at bluewin.ch
Tue Feb 11 20:34:54 CET 2003
"Andrew Koenig" <ark at research.att.com> ha scritto nel messaggio
news:yu99isvqhbgg.fsf_-_ at europa.research.att.com...
> Erik> I'm going to turn that one right around on you. Why add the new
> Erik> keyword `ifelse'? Why not use `if'?
> John> Because you've got a major ambiguity if the statement begins
> John> with an "if". That comment is in the PEP.
> I believe I have eliminated the ambiguity.
> Many people have suggested that it requires unbounded lookahead to
> determine whether
> if C: expr1 else: expr2
> is a statement or an expression. After thinking about it for a while,
> I suddenly realized that this claim is not true.
> The key here is that a statement always ends with either a newline
> or a dedent, and an expression never does. That means that when
> you're parsing bottom-up, whenever it comes time to determine whether
> a construct is an expression or a statement, you can always make that
> determination by seeing whether the next symbol is a newline, a dedent,
> or something else.
> This surprising fact yields an even more surprising simplification
> of my previous proposal for changing the grammar:
> test: and_test ('or' and_test)* | lambdef
> test: and_test ('or' and_test)* | lambdef | if_test
> if_test: 'if' test ':' test ('elif' ':' test)* 'else' ':' test
> In English: An if-else expression is permitted anywhere a lambda
> expression is permitted, with the same precedence rules.
> This change passes pgen without complaint.
> Some implications:
> if x==0: "foo" else: "bar" # legal expression
> if x==0: "foo" # legal statement
> else: "bar"
> print if x==0: "foo" else: "bar" # legal statement
> if x==0: print "foo" else: print "bar" # illegal, as it is today--
> # print is not an expression
brilliant, you've just made the problem worse!
More information about the Python-list