Looking for good explanation of why this code raises SyntaxError.
def echo(x):
return x
def foo(s):
d = {}
exec(s, {}, d)
return dict((x,y) for x,y in d.items())
def bar(s):
d = {}
exec(s, {}, d)
return dict((x, echo(y)) for x,y in d.items()) # comment this to compile
s = 'a=1'
foo(s)
File "test.py", line 11
exec(s, {}, d)
SyntaxError: unqualified exec is not allowed in function 'bar' it contains a
nested function with free variables
In Python 2.x,
execstatements may not appear inside functions that have local “functions” with free variables. A generator expression implicitly defines some kind of “function” (or more precisely, a code object) for the code that should be executed in every iteration. Infoo(), this code only contains references toxandy, which are local names inside the generator expression. Inbar(), the code also contains a reference to the free variableecho, which disqualifiesbar()for the use ofexec.Also note that your
execstatements are probably supposed to readwhich would turn them into qualified exec statements, making the code valid.
Note that your code would work in Python 3.x.
exec()has been turned into a function and can no longer modify the local variables of the enclosing function, thus making the above restriction on the usage ofexecunnecessary.