Hello Ed, It is certainly an odd restriction, but the docs for compile [1] do explicitly state that the input must be newline terminated.
When compiling multi-line statements, two caveats apply: line endings must be represented by a single newline character ('\n'), and the input must be terminated by at least one newline character. I always throw an extra newline onto any input to compile. I think the behaviour maybe for detecting incomplete statements when you pass in the obscure 'don't imply dedent' flag for interactive interpreter loops. [1] http://www.python.org/doc/2.5.2/lib/built-in-funcs.html Michael Foord On Oct 13, 1:06 pm, Ed Leafe <[EMAIL PROTECTED]> wrote: > I've noticed an odd behavior with compile() and code that does not > contain a trailing newline: if the last line is a comment inside of > any block, a syntax error is thrown, but if the last line is a non- > comment Python statement, there is no error. Here's an example (using > 2.5.1 on OS X) > > >>> txt = """ > ... def foo(): > ... print 'bar' """ > >>> compcode = compile(t.strip(), "", "exec") > >>> compcode > <code object <module> at 0x79608, file "", line 2> > > >>> txt += " # Comment on last line" > >>> compcode = compile(txt.strip(), "", "exec") > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "", line 4 > # Comment on last line > ^ > SyntaxError: invalid syntax > >>> compcode = compile(txt.strip() + "\n", "", "exec") > >>> compcode > <code object <module> at 0x79a40, file "", line 2> > > Obviously the easy workaround is to add a newline and all is well, so > this isn't a show-stopper, but is this a bug? > > -- Ed Leafe -- http://www.ironpythoninaction.com/ -- http://mail.python.org/mailman/listinfo/python-list