Python question

Scott David Daniels Scott.Daniels at Acm.Org
Mon Sep 29 19:28:06 EDT 2003


John D. wrote:
> #This program gives: "SyntaxError: unqualified exec is not allowed
> #  in function _ it contains a nested function with free variables"
Here is a (slightly) smaller version that may give you an idea:
     def myfunc(codetext):
         def setvar():
             d[0]=1
         exec codetext
### Causes the error
     def myfunc(codetext):
         def setvar():
             d[0]=1
         exec codetext in globals()
### Does not cause the error

The complaint is about the ambiguity of z's execution environment
(globals and locals), when there is code (setvar) which will reference
the local environment.  Notice that:
def myfunc(codetext):
  	def setvar(d):
  		d[0]=1
  	exec codetext
has no problem: setvar now only looks at its own code.  The question
is not what setvar looks at outside of itself (enclosing function or
globals), but whether it can (potentially) look at any of myfunc's
locals.  If setvar looks at nothing, it doesn't matter whether code
in z potentially creates a local in myfunc or not.

Hope this is enough for you to figure it out.  If not, ask a few more
questions.

-Scott David Daniels
Scott.Daniels at Acm.Org





More information about the Python-list mailing list