469,642 Members | 1,124 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,642 developers. It's quick & easy.

Question about "exec in globals, locals"

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>
Jul 18 '05 #1
2 2225
Hello, Giles!
You wrote on 4 Jul 2003 01:41:36 -0700:

[Snipped]

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

GB> exec source in myglobals, mylocals
exec source in mylocals
exec source in myglobals
And it work with no errors. But I'm not sure you wish this.

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

With best regards, Egor Bolonev. E-mail: eb******@rol.ru [ru eo en]

Jul 18 '05 #2
Hi,
source = """
class FirstClass:
pass
class SecondClass:
References = [FirstClass]
"""

When you specify both locals() and globals(), here's what happen :

"""
class FirstClass:
pass

## ---------> Here, your locals() dict have been updated, but not your
## globals() one.
## But, here, you can do : References = [FirstClass] since your
## locals()
## know about 'FirstClass'

class SecondClass:
## ---------> Here, your locals() dict is a new one since you've
just
## entered a new scope. So, 'FirstClass' is neither defined in
## 'locals()' nor in 'globals()', that's why you have your
NameError
"""

I'm not quite sure of my explanation, but that could explain your
problem. Sorry if I've made any Python mistake.

Cheers,

--
Adrien Di Mascio
LOGILAB, Paris (France).
http://www.logilab.com http://www.logilab.fr http://www.logilab.org
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Mike | last post: by
5 posts views Thread by Toby Donaldson | last post: by
1 post views Thread by kurt.krueckeberg | last post: by
reply views Thread by =?ISO-8859-1?Q?Luis_M._Gonz=E1lez?= | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.