[Python-Dev] Examples for PEP 572
On Wed, Jul 04, 2018 at 10:13:15AM -0700, Devin Jeanpierre wrote:
> > > In Python it'd look like this:
> > >
> > > if x = expr(); x < 0:
> > > do_stuff()
> > Python's parser is restricted to LL(1) by design, so treating semicolons
> > in "if" statements as a special case might not even be possible.
> > But even if it is possible, not only would this special case
> > break the Zen, but it would be UGLY too.
> It isn't a special case, and it's still LL(1). Once you encounter an
> "if", you parse n simple statements separated by a ";", until you
> reach a colon.
I'll take your word about the LL(1).
Did you actually mean arbitrary simple statements?
if import math; mylist.sort(); print("WTF am I reading?"); True:
A more reasonable suggestion would be to only allow *assignments*, not
arbitrary simple statements. But that's another special case:
- everywhere else where a semicolon is legal, it can separate
arbitrary simple statements;
- except inside an if clause, where only assignments are allowed.
> I don't understand why you think this is "clearly" a syntax error.
Taking the principle that semicolons separate statements, you have an
with one or more semicolon-separated statements between the "if" and the
if statement; statement; condition:
If we stick to the rule that semicolons separate statements, that means
if statement # SyntaxError
statement # okay
condition: # SyntaxError
If we don't want that, we need a new rule to treat semicolons
differently inside if statements that they're treated elsewhere.
If we applied this rule "allow statements separated by semicolons"
everywhere, we'd get this:
# I trust you don't want anything even close to these
from x=1; sys import y=2; argv
data x=1; y=2; = sorted(data)
raise x=1; y=2; Exception as err:
So we have to treat semicolons inside if statements differently from
semicolons everywhere else. That what I meant by saying it would be a
The beauty of assignment expressions is that they AREN'T a special case.
Being an expression, they're legal anywhere any other expression is
allowed, and illegal anywhere where expressions aren't allowed.