namespace dictionaries ok?

Ron Adam rrr at ronadam.com
Mon Oct 24 22:53:00 EDT 2005


James Stroud wrote:
> 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

But it's not a dictionary anymore so you can't use it in the same places 
you would use a dictionary.

       foo(**n)

Would raise an error.

So I couldn't do:

    def foo(**kwds):
       kwds = namespace(kwds)
       kwds.bob = 3
       kwds.alice = 5
       ...
       bar(**kwds)     #<--- do something with changed items

Ron


> 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




More information about the Python-list mailing list