Using import in an exec'ed string

Gordon McMillan gmcm at hypernet.com
Sun Aug 5 13:43:26 CEST 2001


Boudewijn Rempt wrote:

> I'm wondering why, if I give a customized globals
> and locals parameter to exec, import doesn't work
> anymore (that is, it doesn't anything to the namespace.):

 
> a="""
> import string
> 
> def f():
>      print string.split("aaa aaa")
> 
> f()"""
> 
> exec(a)

[works]

> exec(a, {}, {})

[fails - NameError on string inside f]

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)

- Gordon





More information about the Python-list mailing list