Dynamic variable names ... with imported libraries.

Terry Reedy tjreedy at udel.edu
Thu May 15 09:35:36 EDT 2003


"Loko" <Loko at caramail.com> wrote in message
news:399d6c30.0305150150.2d7e8bd9 at posting.google.com...
> Hi
>
> I searched for this topic in the archives, and on 1997/04/16, Gred
> Stein wrote :
>
> --------------------
> >>> var = 'spam'
> >>> locals()[var] = 'eggs'
> >>> spam
> 'eggs'
> -------------------

This does not work within functions (as documented, I believe), where
locals() returns a dict that is a *copy* of the local namespace (which
is not a dict):
>>> def f():
...   a = 1
...   print a
...   locals()['a'] = 2
...   print a
...
>>> f()
1
1

It only works at module level because there locals() == globals(), so
it would be less possibly confusing to always use globals(), which
currently does always work.

Terry J. Reedy







More information about the Python-list mailing list