Hacker News new | past | comments | ask | show | jobs | submit login

I would be interest to see this using the __getattr__ rather than __getitem__, so that this is also possible:

  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)
attrdict is indeed a useful thing to have around. I usually base it off on the built in "dict", but as this example shows, it is useful on top of "defaultdict" as well.


Well, it's as trivial as you say. Just set __getattr__ = __getitem__ in your tree.

(Note though that there is/was a small bug(?) in CPython: http://bugs.python.org/issue14658)


Seems like it may take a little more than one line, this errors for me:

  >>> a = tree()
  >>> a.__getattr__ = a.__getitem__


Yea, sure it becomes more than one line (or at least I don't know a good one-line-way) but I wouldn't count that as an issue.

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__
Edit: It doesn't work with the simple assignment because of the mentioned bug. Ofc the fix is trivial. See the code from beagle3.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: