exec throws an exception...why?

Nick Jacobson nicksjacobson at yahoo.com
Sun Jun 6 03:46:11 CEST 2004


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.



More information about the Python-list mailing list