AttrDict
May 29, 2006

A dictionary that can be accessed with the attribute notation, as well as the item notation: using AttrDict, a.b is the same as a["b"]. Also, iterating over an AttrDict yields (key, value) pairs (instead of only keys, as in dicts).

Note, however, that because of the unification of getattr and getitem, you cannot access the type's methods, such as get or keys. You can however use the more explicit notation - AttrDict.<<method>>(<<instance>>, params...).

code

#
# module AttrDict.py
#
class AttrDict(dict):
    __slots__ = []
    
    def __delattr__(self, name):
        try:
            del self[name]
        except KeyError:
            raise AttributeError(name)
    
    def __getattribute__(self, name):
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)
    
    __setattr__ = dict.__setitem__
    __iter__ = dict.iteritems

Example

>>> d = AttrDict()
>>> d
{}
>>> d2 = AttrDict(a=1,b=2)
>>> d2
{'a': 1, 'b': 2}
>>> d.x = 5
>>> d.x
5
>>> d["x"]
5
>>> d["y"] = 7
>>> d
{'y': 7, 'x': 5}
>>>
>>> for k, v in d:
...     print k, "=", v
...
y = 7
x = 5
>>>
>>>
>>>
>>> d.blah = "yada"
>>> d.another_blah = "yada"
>>> d
{'y': 7, 'x': 5, 'blah': 'yada', 'another_blah' : 'yada'}
>>> del d.blah
>>> del d["another_blah"]
>>> d
{'y': 7, 'x': 5}
>>>
>>>
>>>
>>> # this is NOT going to work...
...
>>> d.keys()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 14, in __getattribute__
AttributeError: keys
>>>
>>>
>>> # instead, you'll need to do
...
>>> AttrDict.keys(d)
['y', 'x']
>>>
>>>
>>> AttrDict.update(d, d2)
>>> d
{'y': 7, 'x': 5, 'b': 2, 'a': 1}
>>>