compile() question: SyntaxError: unexpected EOF while parsing

Peter Hansen peter at engcorp.com
Sat Jul 7 09:58:28 EDT 2001


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.)

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.

Unfortunately this means when it or any code which tries
to use the same technique encounters the beginning of the
"else:" block, it terminates with the second exception.

(A workaround appears to be to precede everything with a
dummy "if 1:" block, but I'm trying to learn why the 
built-in compile() doesn't consistently produce the
"unexpected EOF while parsing" message in the second case.)

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list