Using import in an exec'ed string

Boudewijn Rempt boudewijn at tryllian.com
Mon Aug 6 03:54:20 EDT 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
x=1

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

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

f()

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


-- 
Boudewijn | http://www.valdyas.org



More information about the Python-list mailing list