exec throws an exception...why?

fishboy fishboy at spamspamspam.com
Sun Jun 6 04:47:11 CEST 2004


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.

><{{{*>



More information about the Python-list mailing list