Does this class need anything more?
Is there any risk of a lookup loop?
Seems to work...
class attrdict(dict):
"""Dict where d['foo'] also can be accessed as d.foo"""
def __init__(self, *args, **kwargs):
self.__dict__ = self
dict.__init__(s elf, *args, **kwargs)
def __repr__(self):
return dict.__repr__(s elf).join(("att rdict(", ")"))
attrdict({'a': 3, 1: 2, 'b': 4})
attrdict({1: 2, 'c': 4, 'b': 3})
3
5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'attrdict' object has no attribute 'e'
4
2
--
Hallvard
Is there any risk of a lookup loop?
Seems to work...
class attrdict(dict):
"""Dict where d['foo'] also can be accessed as d.foo"""
def __init__(self, *args, **kwargs):
self.__dict__ = self
dict.__init__(s elf, *args, **kwargs)
def __repr__(self):
return dict.__repr__(s elf).join(("att rdict(", ")"))
>>a = attrdict([(1,2)], a=3, b=4)
>>a
>>a
>>a = attrdict([(1,2)], b=3, c=4)
>>a
>>a
>>a.b
>>a.d = 5
>>a['d']
>>a['d']
>>a.e
File "<stdin>", line 1, in ?
AttributeError: 'attrdict' object has no attribute 'e'
>>a.__getattr __ = 'xyzzy'
>>a.__getattrib ute__ = 'xyzzy'
>>a.__setattr __ = 'xyzzy'
>>a.__delattr __ = 'xyzzy'
>>a.c
>>a.__getattrib ute__ = 'xyzzy'
>>a.__setattr __ = 'xyzzy'
>>a.__delattr __ = 'xyzzy'
>>a.c
>>a[1]
>>del a.c
>>>
>>>
Hallvard
Comment