users = tree() users.harold.username = 'hrldcpr' users.handler.username = 'matthandlersux'
class attrdict(defaultdict): def __getattr__(self, key): return self[key] def __setattr__(self, key, val): self[key]=val def tree(): return attrdict(tree)
(Note though that there is/was a small bug(?) in CPython: http://bugs.python.org/issue14658)
>>> a = tree() >>> a.__getattr__ = a.__getitem__
It errors for you because it is a defaultdict instance and doesn't allow attribute overwrites.
This should work:
class tree(defaultdict): def __init__(self): defaultdict.__init__(self, tree) __getattr__ = defaultdict.__getitem__ __setattr__ = defaultdict.__setitem__