exec throws an exception...why?

Nick Jacobson nicksjacobson at yahoo.com
Sun Jun 6 02:24:14 EDT 2004


fishboy <fishboy at spamspamspam.com> wrote in message news:<3415c0lg306oec1a69c3mkolnbhfbku243 at 4ax.com>...
> On 5 Jun 2004 18:46:11 -0700, nicksjacobson at yahoo.com (Nick Jacobson)
> wrote:
> 
> >This works fine:
> >
> >x = 1
> >def execfunc():
> >	print x
> >execfunc()
> >
> >So why doesn't this?
> >
> >s = \
> >"""
> >x = 1
> >def execfunc():
> >	print x
> >execfunc()
> >"""
> >
> >codeobj = compile(s, "<string>", "exec")
> >d = {}
> >e = {}
> >exec codeobj in d, e
> >
> >Error message:
> >Traceback (most recent call last):
> >  File "C:\Nick\proj\python1.py", line 17, in ?
> >    exec codeobj in d, e
> >  File "<string>", line 6, in ?
> >  File "<string>", line 5, in execfunc
> >NameError: global name 'x' is not defined
> >
> >I'm using ActiveState Python 2.3.2 on Windows XP Pro.  Thanks!
> >
> >P.S. It does work if I say
> >exec codeobj in d
> >but I don't understand why.
> 
> It works because the local and global namespaces are both 'd'.  it
> doesn't work in the first because it puts 'x' in the local and then
> looks in global.
> 
> Now, why it puts 'x' in local, I don't know.  If this was a quiz, I'd
> put "Nested Scope" and pray.
> 
> ><{{{*>

I don't know either, that's why I asked ;)

And I don't see why assigning both the local and global namespaces to
the variable 'd' fixes it.  But to answer that, the latter question
has to be addressed first.

--Nick



More information about the Python-list mailing list