namespace dictionaries ok?

James Stroud jstroud at mbi.ucla.edu
Mon Oct 24 22:21:11 EDT 2005


Here it goes with a little less overhead:


py> class namespace:
...   def __init__(self, adict):
...     self.__dict__.update(adict)
...
py> n = namespace({'bob':1, 'carol':2, 'ted':3, 'alice':4})
py> n.bob
1
py> n.ted
3

James

On Monday 24 October 2005 19:06, Ron Adam wrote:
> Hi, I found the following to be a useful way to access arguments after
> they are passed to a function that collects them with **kwds.
>
>
>      class namespace(dict):
>          def __getattr__(self, name):
>              return self.__getitem__(name)
>          def __setattr__(self, name, value):
>              self.__setitem__(name, value)
>          def __delattr__(self, name):
>              self.__delitem__(name)
>
>      def foo(**kwds):
> 	kwds = namespace(kwds)
> 	print kwds.color, kwds.size, kwds.shape  etc....
>
>      foo( color='red', size='large', shape='ball', .... etc..)
>
>
> It just seems awkward to have to use "string keys" in this situation.
> This is easy and still retains the dictionary so it can be modified and
> passed to another function or method as kwds again.
>
> Any thoughts?  Any better way to do this?
>
> Cheers, Ron

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list