Question about "exec in globals, locals"

Giles Brown giles_brown at hotmail.com
Fri Jul 4 10:41:36 CEST 2003


I do not understand why the following code produces
    NameError: name 'FirstClass' is not defined
when both a global and local dict are passed into exec, but
not when only a global dict is passed in.

I seek enlightenment!

Thanks,
Giles Brown

<python_code>

source = """
class FirstClass:
    pass
class SecondClass:
    References = [FirstClass]
"""

# Case - 1
myglobals = {'__builtins__' : None, '__name__': None}
exec source in myglobals

print "Global names are:", myglobals.keys()

# Case - 2
myglobals = {'__builtins__' : None, '__name__': None}
mylocals = {}

exec source in myglobals, mylocals

print "Global names are:", myglobals.keys()
print "Local names are:", mylocals.keys()

</python_code>




More information about the Python-list mailing list