Tag: language python

Python Bunch object or How to make dictionaries act like objects

Programming

Python dictionaries are really powerful, but sometimes you need an object that is a dictionary but it’s also an object which keys are methods of the same object.
Now think if you can have a class called Bunch that makes something like this possible:

bunch = Bunch(a = 7, b = 3, c = 'hello')
In [5]: bunch.a
Out[5]: 7
In [6]: bunch.b
Out[6]: 3
In [7]: bunch.c
Out[7]: 'hello'

But it’s also more powerful than this:

In [9]: d = {'a.b.c':1, 'a.c':2}
In [10]: bunch = Bunch(**d)
In [11]: bunch.a
bunch.a      bunch.a.b.c  bunch.a.c
In [13]: print bunch.a.b.c
1
In [14]: print bunch.a.c
2
In [15]: print bunch['a.b.c']
1

You can also use the dot notation to describe an hierarchy of objects and the Bunch object will take care of it

It’s not a dream, I’ve just implemented this python Bunch Object and this is the code:

class C(object): pass

def rec_getattr(obj, attr):
    """
    Get object's attribute. May use dot notation.
    """
    if '.' not in attr:
        return getattr(obj, attr)
    else:
        L = attr.split('.')
        return rec_getattr(getattr(obj, L[0]), '.'.join(L[1:]))

def rec_setattr(obj, attr, value):
    """
    Set object's attribute. May use dot notation.
    """
    if '.' not in attr:
        setattr(obj, attr, value)
    else:
        L = attr.split('.')
        if not hasattr(obj, L[0]):
            setattr(obj, L[0], C())
        rec_setattr(getattr(obj, L[0]), '.'.join(L[1:]), value)

class Bunch(dict):
    def __init__(self,**kw):
        dict.__init__(self,kw)
        self.__dict__.update(kw)
        for k,v in kw.iteritems():
            rec_setattr(self, k, v) 

Comments, suggestions, patches are welcome 🙂

%d bloggers like this: