Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Valid input, but a nested defaultdict won't let me recursively define items: a.b.c.d.e = 2 as far as I can tell?


It will if you recursively define it:

    from collections import defaultdict
    def dd(): return defaultdict(dd)
    d = dd()
    d['a']['b']['c']  # => defaultdict(dd, {})
    d['a']['b']['c'] = 'test'
    d['a']['b']['c']  # => 'test'


It does recursive access but not attribute access. The problem I see is that attribute access is only part of the problem you're attempting to solve. That's a nice feature but a pretty well known problem (check out the self.__dict__ = self trick) with fairly clear behaviour mimicking the usual dict.

The surprising bit that would stop me dropping this in any real code is that as an end user, it's not immediately clear how the mapping interface should apply to this class. It's all implementation defined but it's not actually defined in the implementation. e.g., Does my Dict() have the key 'a.b.c'? Nope, it only has 'a' and the other keys are managed through some magic. Same.applies to iteration, it might be reasonable to assume that'd be a depth first terminating node iterator but it would actually just iterate the top level of the main Dict instance.


I agree, the code is quite immature. However, your example is a bit off. If you do my_dict.a.b.c = 2, your Dict will only have the key 'a', as it generates nested Dicts. Hopefully you would not expect it to have 'a.b.c' as a key, as imho that would be a bit weird. Needless to say there's a bunch of stuff to figure out, so feel free to submit an issue or PR.




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

Search: