compile() question: SyntaxError: unexpected EOF while parsing

Tim Peters tim.one at home.com
Sat Jul 7 19:48:33 CEST 2001


[Peter Hansen]
> While examining the core of medusa's monitor.py, we've encountered
> a situation that looks on the face of it like an undesirable
> limitation or inconsistency of the Python compiler.  (I fully expect
> to hear an explanation for why this is actually a Good Thing,
> but we haven't figured it out ourselves yet.)

Na, parser error msgs have a life of their own.  You can *try* to change
one, but there's no guarantee it won't change back when you stop glaring at
it <0.9 wink>.

> We expected the following two sequences to produce the same
> exception, but they do not.
>
> >>> good = 'if 1:'
> >>> compile(good, '', 'exec')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<string>", line 1
>     if 1:
>        ^
> SyntaxError: unexpected EOF while parsing
> >>> bad = 'if 1:\n    print 1\nelse:'
> >>> compile(bad, '', 'exec')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<string>", line 3
>     else:
>        ^
> IndentationError: expected an indented block
>
>
> Medusa's monitor.py uses the "unexpected EOF while parsing"
> feature to infer that additional lines of text are going to be
> entered by the user (to satisfy the expected indented block for
> the "if").  This is how it knows when to deliver another "..."
> prompt and when to cancel entry of data and deliver a real
> exception.
> ...

Then it's not smart enough to handle Python code.  Code that is smart enough
can be found in the std library module codeop.py, and people simulating
interpreter loops should use the higher-level facilities in the std code.py.
Getting this right in all cases is tricky (read the code); you've only
bumped into one subtlety so far.

BTW, when reading the code, keep this in mind:

>>> issubclass(IndentationError, SyntaxError)
1
>>>





More information about the Python-list mailing list