I'm learning the basics of eval, exec, and compile on 2.7.6.
I have hit a roadblock on exec, as I get an error when running this:
exec 'print 5'
Error:
SyntaxError: unqualified exec is not allowed in function 'main' it contains a nested function with free variables (EvalExecCompile.py, line 61)
I have found that exec is an expression in 2.7.6 while a function in 3.x. Problem is, I cannot find a working example to learn from for exec in 2.7.6.
I am aware of all the dangers of using exec, etc., but just want to learn how to use them encase I ever need them.
Could someone please help? Maybe provide a working example that I can dissect?
Thank you.
The goal of my question is to learn how to use exec in 2.7.6 properly.
1 Answer 1
You can't use exec in a function that has a subfunction, unless you specify a context. From the docs:
If exec is used in a function and the function contains a nested block with free variables, the compiler will raise a SyntaxError unless the exec explicitly specifies the local namespace for the exec. (In other words, "exec obj" would be illegal, but "exec obj in ns (namespace)" would be legal.)
Here is the code to implement exec:
def test2():
"""Test with a subfunction."""
exec 'print "hi from test2"' in globals(), locals()
def subfunction():
return True
test2()
This example was taken from: In Python, why doesn't exec work in a function with a subfunction?
>>> exec "print 5" 5