I have been trying to convert a simple execution such as:
for x in xrange(10):
if x % 2 == 0:
print x, 'is even'
to a one liner version:
for x in xrange(10): if x % 2 == 0: print x, 'is even'
which gives me:
File "foo.py", line 1
for x in xrange(10): if x % 2 == 0: print x, 'is even'
^
SyntaxError: invalid syntax
I don’t see any ambiguity in here. Is there a particular reason why this fails?
From the formal grammar for 2.7:
If the
suitehad allowed acompound_stmtthen what you suggest would be accepted. But that would also allow something like this:Is that
exceptoutside the enclosingif? Is the call tofoooutside the enclosingif? I think this shows that we really don’t want in-lining compound statements to be allowed by the formal grammar. Simply addingsuite: compound_stmtmakes the grammar ambiguous as I read it, where the same code can be interpreted with two or more different meanings, neither disprovable.Basically, it’s by design that what you ask is a parse error. Reworking the formal grammar could allow the code in your example to work without other funny stuff, but it requires careful attention to ambiguity and other problems.
See also Dangling Else, a grammar problem that afflicted the standard Algol-60 language. It’s not always easy to find these kinds of problems, so a healthy fear of changing a working grammar is a good thing.