Exec woes

Hendrik van Rooyen mail at microcorp.co.za
Tue Jan 27 12:05:00 EST 2009


It starts with the conspiracy of silence at the interactive prompt:

Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
    
IDLE 1.1.3      ==== No Subprocess ====
>>> help(exec)
SyntaxError: invalid syntax
>>>
Its the same under Linux SuSe, Python 2.5.1.

I think this is a BUG.

Anyway, my real problem looks like this:

>>> def Somefunc():
            def excrescence():
                 exec('BUILD = "someString"')
                 return BUILD
 
SyntaxError: unqualified exec is not allowed in function 'excrescence 
it is a nested function (<pyshell#11>, line 3)
>>>

Now this works if it is not nested, and it works if it is a method in a class.
Why the complaint about the nestedness?

I would appreciate it if someone would explain, as the library reference
simply says that it would default to globals() and locals(), which also does
not seem to happen - also true for a "nested" eval after a compile - you have
to specify the globals() or you get a NameError - global BUILD is not defined.

So there is some namespace thing happening that is too subtle for me, and I
would like to know what "unqualified" means in the above message, and
what one must do to "qualify" the statement, if that is what is needed.

The original thing came up because I really need relative imports - I have
some version.py files in various directories that have a single line in them
that looks like the string I am feeding the exec.

By the way, execfile works in this situation, but also only if you specify
globals() explicitly.  I would really like to understand what is going on.

- Hendrik





More information about the Python-list mailing list