Bunch 2.0 - a dict with a default

P

Phlip

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)
 
N

nn

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)

Looks like some combination of defaultdict and namedtuple.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top