Bunch 2.0 - a dict with a default

Chris Kaynor ckaynor at zindagigames.com
Thu Nov 18 20:55:39 EST 2010


You may want to look at the collections.defaultdict class. It takes in a
factory function for default values.

You can also implement your class by overriding the __missing__ method of
the dict class, rather than overriding the __getitem__.

Both were added in Python 2.5 according to the documentation.

Chris


On Thu, Nov 18, 2010 at 5:45 PM, Phlip <phlip2005 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101118/8ec796fa/attachment-0001.html>


More information about the Python-list mailing list