Namespaces, multiple assignments, and exec()

John O'Hagan mail at johnohagan.com
Sat Dec 20 10:27:50 EST 2008


On Sat, 20 Dec 2008, Steven D'Aprano wrote:
> On Sat, 20 Dec 2008 02:53:16 +0000, MRAB wrote:
> > If you're sure you want to use the current namespace then:
> >
> >      for name in namelist:
> >          vars()[name] = func(name, args)
>
> Doesn't work inside a function:
> >>> def parrot():
>
> ...     for name in ['A', 'B', 'C']:
> ...             vars()[name] = ord(name)
> ...     print vars()
> ...     print A
> ...
>
> >>> parrot()
>
> {'A': 65, 'C': 67, 'B': 66, 'name': 'C'}
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 5, in parrot
> NameError: global name 'A' is not defined

Historical note: I found an old post which stated that this used to work in a 
function which invoked exec():
http://mail.python.org/pipermail/python-list/2000-September/050840.html
but I tried it in 2.5 and it doesn't any longer.

Regards,

John





More information about the Python-list mailing list