From 87d9a192423a5a56c4f171b76b722e84d7e162fc Mon Sep 17 00:00:00 2001 From: Marco Cammarata Date: Thu, 9 Feb 2017 14:39:29 +0100 Subject: [PATCH] better handling of empty storage and improved addition of new elements --- storage.py | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/storage.py b/storage.py index cfbb3dc..f363fb3 100644 --- a/storage.py +++ b/storage.py @@ -188,11 +188,14 @@ class DataStorage(dict): self.update( **dict(d) ) def __setitem__(self, key, value): + #print("__setitem__") setattr(self,key,value) super().__setitem__(key, value) def __setattr__(self, key, value): """ allows to add fields with data.test=4 """ + #print("__setattr__") + if isinstance(value,(dict,collections.OrderedDict)): value = DataStorage(value) super().__setitem__(key, value) super().__setattr__(key,value) @@ -208,23 +211,33 @@ class DataStorage(dict): def __repr__(self): keys = list(self.keys()) keys.sort() + if len(keys) == 0: return "Empty DataStorage" nchars = max(map(len,keys)) fmt = "%%%ds %%s" % (nchars) s = ["DataStorage obj containing (sorted): ",] for k in keys: - if isinstance(self[k],np.ndarray): - value_str = "array, size %s, type %s"% ("x".join(map(str,self[k].shape)),self[k].dtype) - elif isinstance(self[k],DataStorage): - value_str = str(self[k])[:50] + "..." - elif isinstance(self[k],(str,DataStorage)): - value_str = self[k][:50] + "..." + obj = self[k] + if isinstance(obj,np.ndarray): + value_str = "array, size %s, type %s"% ("x".join(map(str,obj.shape)),obj.dtype) + elif isinstance(obj,DataStorage): + value_str = str(obj)[:50] + elif isinstance(obj,(str,DataStorage)): + value_str = obj[:50] + elif isinstance(obj,(list,tuple)) and all( [isinstance(v,np.ndarray) for v in obj]): + value_str = "list of arrays, shapes " + ",".join([str(v.shape) for v in obj[:5]]) + " ..." elif self[k] is None: value_str = "None" else: value_str = str(self[k]) + if len(str(obj))>50: value_str += " ..." s.append( fmt % (k,value_str) ) return "\n".join(s) + def keys(self): + keys = list(super().keys()) + keys = [k for k in keys if k != 'filename' ] + return keys + def save(self,fname=None): if fname is None: fname = self.filename assert fname is not None