list/tuple/dict question

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Aug 18 23:09:15 EDT 2008


En Mon, 18 Aug 2008 11:02:20 -0300, gundlach <gundlach at gmail.com> 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.

>From http://docs.python.org/lib/built-in-funcs.html#l2h-47

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()
ns.cat = 1
ns.dog = 2
ns.zoo = ns.cat + ns.dog

-- 
Gabriel Genellina




More information about the Python-list mailing list