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.

Raw_Input
  • 341
  • 1
  • 5
  • 12

1 Answers1

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?

Community
  • 1
  • 1
  • 3
    Actually, this whole answer was taken from another answer on the original question: http://stackoverflow.com/a/4484946/2555451 –  Jan 10 '15 at 02:21
  • 1
    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. – Ganesh Kamath - 'Code Frenzy' Jan 10 '15 at 02:23
  • 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). –  Jan 10 '15 at 02:27
  • I'm back on the Python road with exec. Thanks all. – Raw_Input Jan 10 '15 at 02:27
  • 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', '', 'exec') >>> ns = {}' >>> exec code in ns >>> print ns['a'] 3 [link](http://lucumr.pocoo.org/2011/2/1/exec-in-python/) – Raw_Input Jan 10 '15 at 02:44