From ca180faa157589645754310971bd0af22597f992 Mon Sep 17 00:00:00 2001 From: Fredrik Tolf Date: Fri, 20 Mar 2015 06:15:35 +0100 Subject: [PATCH] Added autostore convenience type. --- didex/store.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/didex/store.py b/didex/store.py index 450a9fe..fb5f2c6 100644 --- a/didex/store.py +++ b/didex/store.py @@ -83,16 +83,37 @@ class store(object): return id @txnfun(lambda self: self.db().env.env) - def unregister(self, id, *, tx): + def unregister(self, id, *, vfy=None, tx): obj = self.get(id) + if vfy is not None and obj is not vfy: + raise RuntimeError("object identity crisis: " + str(vfy) + " is not cached object " + obj) for nm, attr in storedescs(obj): attr.unregister(id, obj, tx) self.db().remove(id, tx=tx) self.cache.remove(id) @txnfun(lambda self: self.db().env.env) - def update(self, id, *, tx): + def update(self, id, *, vfy=None, tx): obj = self.get(id, load=False) + if vfy is not None and obj is not vfy: + raise RuntimeError("object identity crisis: " + str(vfy) + " is not cached object " + obj) for nm, attr, in storedescs(obj): attr.update(id, obj, tx) self.db().replace(id, self._encode(obj), tx=tx) + +class autotype(type): + def __call__(self, *args, **kwargs): + new = super().__call__(*args, **kwargs) + new.id = self.store.register(new) + return new + +class autostore(object, metaclass=autotype): + def __init__(self): + self.id = None + + def save(self): + self.store.update(self.id, vfy=self) + + def remove(self): + self.store.unregister(self.id, vfy=self) + self.id = None -- 2.11.0