[issue24800] Incorrect handling of local variables in comprehensions with exec()
New submission from Peter Eastman: The following script demonstrates a bug in the exec() function in Python 3.4. (It works correctly in 2.7). script = """ print(a) print([a for i in range(5)]) """ exec(script, globals(), {"a":5}) It produces the following output: 5 Traceback (most recent call last): File "test.py", line 5, in exec(script, globals(), {"a":5}) File "", line 3, in File "", line 3, in NameError: name 'a' is not defined The variable "a" is getting passed to the script, as expected: printing it out works correctly. But if you use it in a comprehension, the interpreter claims it does not exist. -- messages: 248064 nosy: Peter Eastman priority: normal severity: normal status: open title: Incorrect handling of local variables in comprehensions with exec() type: behavior versions: Python 3.4 ___ Python tracker <http://bugs.python.org/issue24800> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24800] Incorrect handling of local variables in comprehensions with exec()
Peter Eastman added the comment: I don't believe that explanation is correct. You can just as easily get the same problem without explicitly passing a map to exec(). For example: def f(): script = """ print(a) print([a for i in range(5)]) """ a = 5 exec(script) f() The documentation for exec() states, "In all cases, if the optional parts are omitted, the code is executed in the current scope." Therefore the code above should be exactly equivalent to the following: def f(): a = 5 print(a) print([a for i in range(5)]) f() But the latter works and the former doesn't. Contrary to the documentation, the code is clearly not being executed in the same scope. -- resolution: not a bug -> status: closed -> open ___ Python tracker <http://bugs.python.org/issue24800> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24800] Incorrect handling of local variables in comprehensions with exec()
Peter Eastman added the comment: Then fix the documentation. This behavior directly contradicts the documentation of the exec() function. The question is not what scope the comprehension runs in, it's what scope the script runs in. See my third example. A comprehension in the f() function has no problem seeing local variables defined in that function. If the script were running into the same scope as that function, then comprehensions inside the script would also see those variables. They don't, clearly demonstrating that the script does *not* run in the same scope, and contradicting the documentation. -- resolution: not a bug -> status: closed -> open ___ Python tracker <http://bugs.python.org/issue24800> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com