fix utils.LazyProperty
authorTero Marttila <terom@fixme.fi>
Fri, 05 Jun 2009 23:41:57 +0300
changeset 75 18b3b1926720
parent 74 3bf1adf13fdf
child 76 e22d9f699081
fix utils.LazyProperty
degal/utils.py
--- a/degal/utils.py	Fri Jun 05 23:06:13 2009 +0300
+++ b/degal/utils.py	Fri Jun 05 23:41:57 2009 +0300
@@ -9,12 +9,17 @@
         Lazy-loaded properties
     """
 
+    ATTRNAME = '_LazyProperty_values'
+
     def __init__ (self, func) :
         """
             Initialize with no value
         """
 
         super(LazyProperty, self).__init__(func)
+        
+        self.func = func
+        self.name = func.__name__
 
         self.value = None
 
@@ -23,35 +28,52 @@
             Run the background func and return the to-be-cached value
         """
 
-        return super(LazyProperty, self).__call__(obj)
+        return self.func(obj)
  
+    def obj_dict (self, obj):
+        """
+            Get the lazy-property dict of the given obj
+        """
+
+        dict = getattr(obj, self.ATTRNAME, None)
+
+        if dict is None :
+            dict = {}
+
+            setattr(obj, self.ATTRNAME, dict)
+
+        return dict
+
     def get (self, obj) :
         """
             Return the cached value
         """
 
-        xxx
+        return self.obj_dict(obj)[self.name]
     
     def set (self, obj, value) :
         """
             Set the cached value
         """
 
-        xxx
+        self.obj_dict(obj)[self.name] = value
 
     def test (self, obj) :
         """
             Tests if a value is set
         """
 
-        xxx
+        return self.name in self.obj_dict(obj)
        
-    def __call__ (self, obj) :
+    def __get__ (self, obj, owner) :
         """
             Return the cached value if it exists, otherwise, call the func
         """
 
-        if self.test(obj):
+        if not obj :
+            return self
+
+        if not self.test(obj) :
             # generate it
             self.set(obj, self.run(obj))