NEW TO THIS: Assigning values to strings in list?

Alex Martelli aleax at aleax.it
Sat Jul 20 04:35:33 EDT 2002


Chris Liechti wrote:
        ...
>>> Johannes Graumann <graumann at clyde.caltech.edu> wrote in
>>>>>names = ["one","two","three"]
>>>>>values = [ 1,2,3]
>> --> DO SOMETHING HERE
>>>>>print one
>> 1
> 
> my tip: don't pollute the global namespace.

Seconded!  Don't pollute local ones either, btw:-).

> if you do it with a class it's easier anyway:
> 
>>>> class Lexikon:
> ...   def __init__(self, values):
> ...           self.__dict__.update(values)
> ...
>>>> l = Lexikon(dict(zip(names,values)))
>>>> l.one
> 1

Yay, the good old Bunch idiom.  You can do a tiny
bit better if this specific use is widespread for you:

class Namespace:
    def __init__(self, names, values):
        self.__dict__ = dict(zip(names,values))

n = Namespace(names, values)
print n.one

but that's a factoring detail.  The key idea is that
said little innoucous-looking l. or n. before the
dynamically determined name saves a LOT of problems.

Namespaces are a honking great idea.  Let's do more of those.


Alex




More information about the Python-list mailing list