is it a bug in exec?

Peter Otten __peter__ at web.de
Fri Jan 21 12:00:32 EST 2011


longqian9509 at gmail.com wrote:

> In pyhton 3.1, I found the following code will succeed with argument 1
> to 4 and fail with argument 5 to 9. It is really strange to me. I
> suspect it may be a buy in exec() function. Does anyone have some idea
> about it? Thanks.
> 
> 
> t1="""
> class foo:
> def fun():
> print('foo')
> def main():
> global foo
> foo.fun()
> main()
> """
> t2="""
> class foo:
> def fun():
> print('foo')
> def main():
> foo.fun()
> main()
> """
> 
> import sys
> import copy
> if sys.argv[1]=='1':
> exec(t1)
> elif sys.argv[1]=='2':
> exec(t2)
> elif sys.argv[1]=='3':
> exec(t1,{},{})
> elif sys.argv[1]=='4':
> exec(t2,globals(),locals())
> elif sys.argv[1]=='5':
> exec(t2,{},{})
> elif sys.argv[1]=='6':
> exec(t2,globals(),{})
> elif sys.argv[1]=='7':
> exec(t2,{},locals())
> elif sys.argv[1]=='8':
> exec(t2,copy.copy(globals()),locals())
> elif sys.argv[1]=='9':
> exec(t2,globals(),copy.copy(locals()))

There are only two cases that matter: identical local/global namespaces and 
distinct local/global namespaces:

>>> code = """\
... x = 42 # put x into the local namespace
... def f():
...     print(x) # look up x in the global namespace
... f()
... """
>>> exec(code, {}, {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 4, in <module>
  File "<string>", line 3, in f
NameError: global name 'x' is not defined
>>> ns = {}
>>> exec(code, ns, ns)
42

Also note that

>>> globals() is locals()
True

on the module level.

Peter



More information about the Python-list mailing list