Live data from Hacker News

One-line Tree In Python

gist.github.com

1–10 of 38 posts

Re: One-line Tree In Python

#4
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'

Re: One-line Tree In Python

#5
This is actually quite elegant and useful. I've done similar things time and time again with code like so:

    defaultdict(lambda: defaultdict(int))
That allows me to organically build dictionaries (mainly for stat building) using operands like +=.

Re: One-line Tree In Python

#6
post #4

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'

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)

Re: One-line Tree In Python

#7
post #4

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.

Re: One-line Tree In Python

#8
post #3

In Perl, this is called autovivification: https://en.wikipedia.org/wiki/Autovivification I've wanted something like that in Python at different times... thanks! edit: Ha! The Wiki article even has basically the same code: def hash(): return defaultdict(hash)

wow thanks i was actually really curious if there was a name for this sort of thing! added a note about it to the gist.

i wonder whether it will be made part of more languages as JSON-esque nested objects proliferate in our code and minds.

Re: One-line Tree In Python

#9
Neat. Works in Ruby, too.

  def tree; Hash.new {|h, k| h[k] = tree }; end
  t = tree
  t[:foo][:bar] = "foobar"  # => {:foo=>{:bar=>"foobar"}}
Probably more idiomatic to do it as a class, though.

  class Tree 
Btw. How do you post nicely formatted code?

edit - Thanks!

Post reply on HN