diff --git a/src/attrdict.py b/src/attrdict.py index 8fb9a97..ff20f0f 100644 --- a/src/attrdict.py +++ b/src/attrdict.py @@ -29,8 +29,7 @@ class AttrDict(dict): self.__dict__ = self def copy(self): - ch = AttrDict(self) - return ch + return AttrDict(self) def __repr__(self): return 'AttrDict(' + dict.__repr__(self) + ')' diff --git a/src/storage.py b/src/storage.py new file mode 100644 index 0000000..0839377 --- /dev/null +++ b/src/storage.py @@ -0,0 +1,86 @@ +# Developed by Massimo Di Pierro . +# License: GPL v2 + +class Storage(dict): + """ A Storage object is like a dictionary except `obj.foo` can be used + in addition to `obj['foo']`. """ + def __getattr__(self, key): + try: + return self[key] + except KeyError, k: + return None + + def __setattr__(self, key, value): + self[key] = value + + def __delattr__(self, key): + try: + del self[key] + except KeyError, k: + raise AttributeError, k + + def __repr__(self): + return 'Storage(' + dict.__repr__(self) + ')' + + def __getstate__(self): + return dict(self) + + def __setstate__(self, value): + for (k, v) in value.items(): + self[k] = v + + def copy(self): + return Storage(self) + + @classmethod + def fromkeys(self, seq, value = None): + return Storage(dict.fromkeys(seq, value)) + + +if __name__ == "__main__": + # test cases provided by Gabriel Genellina + from pickle import loads, dumps + assert Storage() == {} + d1 = {1:2, '3':4, 'name': 'value', '__getattr__': 5, '__getitem__': 6} + d2 = Storage(d1) + assert d1 == d2 + + assert d2.copy() == d2 + assert isinstance(d2.copy(), type(d2)) + assert eval(repr(d2)) == d2 + assert isinstance(eval(repr(d2)), type(d2)) + + d3 = Storage.fromkeys([1,2,3]) + assert isinstance(d3, Storage) + assert d3 == {1:None, 2:None, 3:None} + + assert d2[1] == 2 + assert d2['name'] == d2.name == 'value' + assert d2.__getattr__ == 5 + + assert not hasattr(d2, 'xyz') + assert 'xyz' not in d2 + d2.xyz = 123 + assert d2.xyz == d2['xyz'] == 123 + assert 'xyz' in d2 + + d2['xyz'] = 456 + assert d2['xyz'] == d2.xyz == 456 + assert hasattr(d2, 'xyz') + + d2['abc'] = 789 + assert d2.abc == d2['abc'] == 789 + + d2.abc = 123 + assert d2.abc == d2['abc'] == 123 + + del d2.abc + assert not hasattr(d2, 'abc') + assert 'abc' not in d2 + del d2['xyz'] + assert not hasattr(d2, 'xyz') + assert 'xyz' not in d2 + + d4 = loads(dumps(d2)) + assert d2 == d4 + assert isinstance(d4, type(d2)) \ No newline at end of file