Added idlink.
authorFredrik Tolf <fredrik@dolda2000.com>
Thu, 1 Feb 2018 03:51:52 +0000 (04:51 +0100)
committerFredrik Tolf <fredrik@dolda2000.com>
Thu, 1 Feb 2018 03:51:52 +0000 (04:51 +0100)
didex/values.py

index a4473f0..bff26e7 100644 (file)
@@ -2,7 +2,7 @@ import threading
 from . import store, lib, index
 from .store import storedesc
 
-__all__ = ["simple", "multi", "compound"]
+__all__ = ["simple", "multi", "compound", "idlink"]
 
 class cursor(lib.closable):
     def __init__(self, bk, st):
@@ -162,3 +162,21 @@ class compound(base):
             idx.remove(ival, id, tx=tx)
             idx.put(val, id, tx=tx)
             tx.postcommit(lambda: setattr(obj, self.iattr, val))
+
+class idlink(object):
+    def __init__(self, name, atype):
+        self.atype = atype
+        self.battr = "__idlink_%s" % name
+
+    def __get__(self, obj, cls):
+        if obj is None: return self
+        ret = self.atype.store.get(getattr(obj, self.battr))
+        assert isinstance(ret, self.atype)
+        return ret
+
+    def __set__(self, obj, val):
+        assert isinstance(val, self.atype)
+        setattr(obj, self.battr, val.id)
+
+    def __delete__(self, obj):
+        delattr(obj, self.battr)