3 ms·
I think you could implement it like this: from collections import defaultdict class D(defaultdict): def __init__(self): super(D,
by tyrion 12y ago
I think you could implement it like this:
from collections import defaultdict
class D(defaultdict):
def __init__(self):
super(D, self).__init__(D)
__getattr__ = defaultdict.__getitem__
__setattr__ = defaultdict.__setitem__
__repr__ = dict.__repr__
- BerislavLopac 12y agoYou think right.
- zb 12y agoAlmost, he is also converting ordinary dicts that get added as items to his own Dict class to enable you to keep using this syntax further down the tree, so you'd need a small wrapper around __setitem__. But yes, the idea of storing everything twice (once as an item and once as an attribute) just so you can unconditionally add defaults in __getattr__ is… bizarre and will break things horribly as soon as you accidentally do something like: myDict['get'] = 'foo'
- deleted 12y ago[deleted]
- tyrion 12y ago> Almost, he is also converting ordinary dicts that get added as items to his own Dict class You are right I dind't notice that before. But looking at the code it seems that the only permitted values are dict and str?! > But yes, the idea of storing everything twice (once as an item and once as an attribute) I don't get that, you don't store things twice and nothing breaks, at least with the example code I wrote above. Try: >>> a=D() >>> a.lol = 2 >>> a['get'] = 'foo' >>> a {'get': 'foo', 'lol': 1} >>> vars(a) {}
- hueving 12y agoBut if you do it like that, it's almost not worth packaging into a library and posting to hackernews. :)
- ntoshev 12y agoThis doesn't trigger autocompletion of attributes in dreampie / bpython / ipython - the original implementation does.
- mewwts 12y agoThis is true!
- mewwts 12y agoThis is neat! Super close to what I want in much less code :-)