Bunch 2.0 - a dict with a default

nn pruebauno at latinmail.com
Fri Nov 19 09:25:12 EST 2010


On Nov 18, 8:45 pm, Phlip <phlip2... at gmail.com> wrote:
> Pythonistas:
>
> If everyone likes this post, then the code is a "snippet" for
> community edification. Otherwise, it's a question: How to do this kind
> of thing better?
>
> I want a dict() variant that passes these test cases:
>
>         map = Map()
>         assert not(map.has_key('_default'))
>
>         map = Map(yo='dude')
>         assert map['yo'] == 'dude'
>         assert map.yo == 'dude'
>         assert None == map['whatever']
>         assert not(map.has_key('_default'))
>
>         map = Map(yo='dude', _default='q')
>         assert 'q' == map['whatever']
>         assert not(map.has_key('_default'))
>
> That's like Bunch, but with a default value. (That makes code with
> excess if statements less likely.)
>
> So here's the implementation:
>
> def Map(*args, **kwargs):
>     value = kwargs.get('_default', None)
>     if kwargs.has_key('_default'):  del kwargs['_default']
>
>     class _DefMap(dict):
>         def __init__(self, *a, **kw):
>             dict.__init__(self, *a, **kw)
>             self.__dict__ = self
>
>         def __getitem__(self, key):
>             if not self.has_key(key):  self[key] = value
>             return dict.__getitem__(self, key)
>
>     return _DefMap(*args, **kwargs)
>
> --
>   Phlip
>  http://bit.ly/ZeekLand

Looks like some combination of defaultdict and namedtuple.



More information about the Python-list mailing list