[Checkins] SVN: zope.cachedescriptors/trunk/src/zope/cachedescriptors/property. added property.cachedIn which allows to cache properties in a specified attribute.

Christian Zagrodnick cz at gocept.com
Wed May 9 09:11:30 EDT 2007


Log message for revision 75652:
  added property.cachedIn which allows to cache properties in a specified attribute.

Changed:
  U   zope.cachedescriptors/trunk/src/zope/cachedescriptors/property.py
  U   zope.cachedescriptors/trunk/src/zope/cachedescriptors/property.txt

-=-
Modified: zope.cachedescriptors/trunk/src/zope/cachedescriptors/property.py
===================================================================
--- zope.cachedescriptors/trunk/src/zope/cachedescriptors/property.py	2007-05-09 13:02:21 UTC (rev 75651)
+++ zope.cachedescriptors/trunk/src/zope/cachedescriptors/property.py	2007-05-09 13:11:30 UTC (rev 75652)
@@ -85,3 +85,22 @@
 
         func = self.func
         return func(inst)
+
+
+class cachedIn(object):
+    """Cached property with given cache attribute."""
+
+    def __init__(self, attribute_name):
+        self.attribute_name = attribute_name
+
+    def __call__(self, func):
+
+        def get(instance):
+            try:
+                value = getattr(instance, self.attribute_name)
+            except AttributeError:
+                value = func(instance)
+                setattr(instance, self.attribute_name, value)
+            return value
+
+        return property(get)

Modified: zope.cachedescriptors/trunk/src/zope/cachedescriptors/property.txt
===================================================================
--- zope.cachedescriptors/trunk/src/zope/cachedescriptors/property.txt	2007-05-09 13:02:21 UTC (rev 75651)
+++ zope.cachedescriptors/trunk/src/zope/cachedescriptors/property.txt	2007-05-09 13:11:30 UTC (rev 75652)
@@ -155,3 +155,47 @@
     >>> '%.2f' % point.radius
     computing radius
     '2.24'
+
+
+cachedIn
+========
+
+The `cachedIn` property allows to specify the attribute where to store the
+computed value::
+
+    >>> class Point:
+    ... 
+    ...     def __init__(self, x, y):
+    ...         self.x, self.y = x, y
+    ...
+    ...     @property.cachedIn('_radius_attribute')
+    ...     def radius(self):
+    ...         print 'computing radius'
+    ...         return math.sqrt(self.x**2 + self.y**2)
+    
+    >>> point = Point(1.0, 2.0)   
+
+    >>> '%.2f' % point.radius
+    computing radius
+    '2.24'
+
+    >>> '%.2f' % point.radius
+    '2.24'
+
+The radius is cached in the attribute with the given name, `_radius_attribute`
+in this case::
+
+    >>> '%.2f' % point._radius_attribute
+    '2.24'
+
+When the attribute is removed the radius is re-calculated once. This allows
+invalidation::
+
+    >>> del point._radius_attribute
+
+    >>> '%.2f' % point.radius
+    computing radius
+    '2.24'
+
+    >>> '%.2f' % point.radius
+    '2.24'



More information about the Checkins mailing list