list/tuple/dict question

Gabriel Genellina gagsl-py2 at
Tue Aug 19 05:09:15 CEST 2008

En Mon, 18 Aug 2008 11:02:20 -0300, gundlach <gundlach at> escribió:

> In C or C++, what you want to do is impossible.  However, in Python,
> there's a way to specify the name of a local variable at runtime:
> locals()['cat'] = []
> locals() is a function call that returns a dictionary mapping all
> local variable names to their values.  Just like "foo[0] = []" above
> will store an empty list into the 0th item in foo, "locals()['cat'] =
> []" will store an empty list in the 'cat' entry in the locals
> dictionary.


locals(): Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. 

So modifying locals() is unsafe at least. Do as everyone else suggested and use a dictionary. If using ns['cat'] really annoys you so much, define a generic attribute container:

class NS(object): pass

ns = NS() = 1 = 2
ns.zoo = +

Gabriel Genellina

More information about the Python-list mailing list