Bunch 2.0 - a dict with a default

Phlip phlip2005 at gmail.com
Fri Nov 19 02:45:04 CET 2010


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



More information about the Python-list mailing list