degal/utils.py
changeset 84 891545a38a2b
parent 75 18b3b1926720
child 96 d9cf1e272e90
--- a/degal/utils.py	Wed Jun 10 23:32:29 2009 +0300
+++ b/degal/utils.py	Wed Jun 10 23:33:28 2009 +0300
@@ -6,11 +6,12 @@
 
 class LazyProperty (property) :
     """
-        Lazy-loaded properties
+        Lazy-loaded cached properties.
+
+        This functions by overriding the class's property attribute with the actual value attribute in the instance's
+        dict, causing all future attribute lookups to return that directly.
     """
 
-    ATTRNAME = '_LazyProperty_values'
-
     def __init__ (self, func) :
         """
             Initialize with no value
@@ -18,66 +19,41 @@
 
         super(LazyProperty, self).__init__(func)
         
+        # the getter function
         self.func = func
+
+        # the attribute name
         self.name = func.__name__
 
-        self.value = None
-
     def run (self, obj) :
         """
-            Run the background func and return the to-be-cached value
+            Run the background func and return the to-be-cached value.
+
+            `obj` is the object instance
         """
 
         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) :
+    def store (self, obj, value) :
         """
-            Return the cached value
-        """
-
-        return self.obj_dict(obj)[self.name]
-    
-    def set (self, obj, value) :
-        """
-            Set the cached value
+            Store the cached value, overring ourself
         """
-
-        self.obj_dict(obj)[self.name] = value
+        
+        obj.__dict__[self.name] = value
 
-    def test (self, obj) :
-        """
-            Tests if a value is set
-        """
-
-        return self.name in self.obj_dict(obj)
-       
     def __get__ (self, obj, owner) :
         """
-            Return the cached value if it exists, otherwise, call the func
+            Generate the value, store it as the attribute and return it.
         """
+        
+        # compute value
+        value = self.run(obj)
 
-        if not obj :
-            return self
-
-        if not self.test(obj) :
-            # generate it
-            self.set(obj, self.run(obj))
-
-        return self.get(obj)
+        # store it
+        self.store(obj, value)
+        
+        # return it
+        return value
 
 class LazyIteratorProperty (LazyProperty) :
     """