Using import in an exec'ed string

Boudewijn Rempt boudewijn at
Mon Aug 6 09:54:20 CEST 2001

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 following script shows a bit of my experiments:

print "GLOBALS:\t", globals()
print "LOCALS:\t\t", locals()

s = """
import string

if globals().has_key("string"): print "OOOK"
if locals().has_key("string"): print "EEEK"

def f():
    print string.split("xxx xxx")


print "=======: Kaal"
exec s
print "=======: Empty dicts"
exec (s, {})
print "=======: Empty dicts from vars"
exec (s, g)
print "=======: Messed up dicts"
g["x"] = 10
exec s in g
print "=======: Functions"
g["x"] = 10
exec (s, globals(), globals())

Boudewijn |

More information about the Python-list mailing list