1

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.

asked Jan 10, 2015 at 2:09
2
  • in 2.7.2 it works fine. >>> exec "print 5" 5 Commented Jan 10, 2015 at 2:16
  • Thanks, that answer is what I needed. I really did search this to death before asking. Commented Jan 10, 2015 at 2:17

1 Answer 1

3

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?

answered Jan 10, 2015 at 2:16
Sign up to request clarification or add additional context in comments.

5 Comments

Actually, this whole answer was taken from another answer on the original question: stackoverflow.com/a/4484946/2555451
i have modified the answer to meet this questions requirement. I have also mentioned clearly where this answer was taken from. In the past when i pasted links, i used to get comments saying i should paste the most relavent part.
That doesn't mean it is OK to copy/paste an existing answer, even if you give attribution. Linking to another answer should be to give support your own answer. You just posted the exact same text again over here (and threw out a few words).
I'm back on the Python road with exec. Thanks all.
After understanding the answer, I began to understand what was being shown at another site. Specifically, you can define your own namespace and then use exec withing it. '>>> code = compile('a = 1 + 2', '<string>', 'exec') >>> ns = {}' >>> exec code in ns >>> print ns['a'] 3 link

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.