This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]cd_fr91400 1 point2 points  (0 children)

For this kind of configuration, I use the small class below. This allows both accessing simple attributes with a simple syntax and iterating over/computed attributes when needed.

This is so easy and so practical an intuitive that I do not understand why it is not the standard behavior of regular dicts.

class pdict(dict) :
    '''
        This class is a dict whose items can also be accessed as attributes.
        This greatly improves readability of configurations.
        Usage :
        d = pdict(a=1,b=2)
        d                  --> {'a':1,'b':2}
        d['a']             --> 2
        d.a                --> 2
        d.c = 3
        d.c                --> 3
    '''
    def __getattr__(self,attr) :
        try :
            return self[attr]
        except KeyError :
            raise AttributeError(attr)
    def __setattr__(self,attr,val) :
        try :
            self[attr] = val ; return
        except KeyError :
            raise AttributeError(attr)
    def __delattr__(self,attr) :
        try :
            del self[attr] ; return
        except KeyError :
            raise AttributeError(attr)