Using import in an exec'ed string

Bernhard Herzog bh at intevation.de
Mon Aug 6 06:33:10 EDT 2001


Boudewijn Rempt <boudewijn at tryllian.com> writes:

> Gordon McMillan wrote:
> 
> > Nothing to do with import. This fails too:
> > 
> > a = """
> > x = 3
> > def f():
> >   print x
> > f()
> > """
> > exec(a, {}, {})
> > 
> > But, this works:
> > d = {}
> > exec(a, d, d)
> > 
> 
> I've now determined that the breaking factor is the passing of 
> a locals variable. I don't know why - wish I would, because I
> want to explain the behaviour in a chapter on implementing macro
> extensions for Python applications. (There is an ominous sentence on
> messing with locals in the language reference, though).

The reason it fails is that if you provide a locals dict all name
bindings on the outermost level will be put into the locals dict, but
not into the globals dict. The function f has its own locals of course
and can't access the names in the exec's locals. This is similar to the
situation of nested functioins where the inner function can't access the
local names of the surrounding functions.

Playing around with this a bit, I found that this happens even with
nested scopes:

Python 2.2a1 (#1, Jul 19 2001, 19:38:55) 
[GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> g = {}
>>> l = {}
>>> s = """
... import string
... def f():
... 	string.split("a b")
... f()
... """
>>> exec s in g, l  
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<string>", line 5, in ?
  File "<string>", line 4, in f
NameError: global name 'string' is not defined
>>> 

It seems to me that with nested scopes f should be able to access the
surrounding scope's names.

   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                               http://mapit.de/



More information about the Python-list mailing list