[Python-ideas] question - 'bag' type

Masklinn masklinn at masklinn.net
Thu Apr 15 11:29:16 CEST 2010


On 15 Apr 2010, at 09:31 , M.-A. Lemburg wrote:
> 
> C. Titus Brown wrote:
>> Hi all,
>> 
>> this seems like the right forum to ask -- is there a reason why Python
>> doesn't have a 'bag' builtin type, e.g.
>> 
>>   b = bag(foo=bar, baz=bif)
>> 
>>   assert b.foo == bar
>>   assert b.bz == bif
>> 
>> ?
> 
> That's what's normally called a "namespace" in Python-land
> and can easily be had via a regular instance:
> 
> class Namespace:
>    def __init__(self, **kws):
>        self.__dict__.update(kws)
> 
> b = Namespace(foo=bar, baz=bif)

An other way is to inherit from dict and just forward __getattr__
 and __setattr__ to __getitem__ and __setitem__ (with exception conversion
maybe), that way both accesses are possible, and you get all the dicty
goodness for free (dict merging with both arg and **kwargs constructor 
arguments, iterations, string representation, `dict.update`, …)

class NS(dict):
    def __getattr__(self, key):
        return self.__getitem__(key)
    def __setattr__(self, key, value):
        return self.__setitem__(key, value)
    def __delattr__(self, key):
        return self.__delitem__(key)

(note: that one probably breaks `hasattr` and `getattr` given KeyError isn't
converted to AttributeError, but that should not take many lines)


More information about the Python-ideas mailing list