is it a bug in exec?

long longqian9509 at gmail.com
Fri Jan 21 16:19:47 EST 2011


I see now. Thank you so much.
I think namespace is really a confusing part in Python.

On Friday, January 21, 2011 11:00:32 AM UTC-6, Peter Otten wrote:
> 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