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
R. David Murray added the comment:
Yes it is. The comprehension is a *new* scope, within the outer scope of the
exec, and it *cannot see* the variables in the outer scope of the exec. You
have the same problem if you try to use a comprehension in that way in a class
statement at the class le
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 d
R. David Murray added the comment:
exec is subtle. See the explanation linked from issue 23087, which while not
*exactly* on point explains the underlying problem (a comprehension is a new
scope, and exec can't reach an intermediate scope the way a compiled function
can).
As far as the diffe
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 cal