namespace dictionaries ok?

Duncan Booth duncan.booth at invalid.invalid
Tue Oct 25 03:31:54 EDT 2005


Ron Adam wrote:
> James Stroud wrote:
>> Here it goes with a little less overhead:
>> 
>> 
<example snipped>
> 
> 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
> 
I agree with Steven D'Aprano's reply, but if you are set on it you could 
try this:

>>> class namespace(dict):
	def __init__(self, *args, **kw):
	    dict.__init__(self, *args, **kw)
	    self.__dict__ = self

	    
>>> n = namespace({'bob':1, 'carol':2, 'ted':3, 'alice':4})
>>> n.bob
1
>>> n.bob = 3
>>> n['bob']
3

The big problem of course with this sort of approach is that you cannot 
then safely use any of the methods of the underlying dict as they could be 
masked by values.

P.S. James, *please* could you avoid top-quoting.



More information about the Python-list mailing list