Bug when using with_statement with exec

Matimus mccredie at gmail.com
Mon Jul 14 18:00:32 EDT 2008


I think I'm going to create a new issue in Pythons issue database, but
I wanted to run it by the news group first. See if I can get any
useful feed back.

The following session demonstrates the issue:

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exec "def foo():\n    return 0" # no ending newline works fine
>>> foo()
0
>>> exec "def foo():\n    return 1\n" # with an ending newline works fine
>>> foo()
1
>>> from __future__ import with_statement
>>> exec "def foo():\n    return 2\n" # with an ending newline works fine
>>> foo()
2
>>> exec "def foo():\n    return 3" # without an ending new line... breaks
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 2
    return 3
          ^
SyntaxError: invalid syntax



If I create a function by using exec on a string and _don't_ end the
string with a new-line it will work just fine unless I "from
__future__ import with_statement". I can imagine that it is probably a
good practice to always end function body's with a new-line, but the
requirement should be consistent and the syntax error text could be a
_little_ more descriptive (and flag something other than the 2nd to
last character). Note that you don't need to be in the interpreter to
reproduce this issue.

I searched python's issue database and didn't see anything similar to
this. If there is already an issue related to this, please point me to
it... or better yet, let me know how you found it.

Matt



More information about the Python-list mailing list