Added property annotation to define volatile attributes on persistent classes
authorThierry Florac <thierry.florac@onf.fr>
Fri, 26 Jan 2018 15:34:40 +0100
changeset 130 9dd00059a845
parent 129 d0f4ef05c378
child 131 d702d2bf095a
Added property annotation to define volatile attributes on persistent classes
src/pyams_utils/zodb.py
--- a/src/pyams_utils/zodb.py	Fri Jan 26 15:33:55 2018 +0100
+++ b/src/pyams_utils/zodb.py	Fri Jan 26 15:34:40 2018 +0100
@@ -274,7 +274,6 @@
         self._storage.close()
 
     # Context manager methods
-
     def __enter__(self):
         connection = self.get_connection()
         return connection.root()
@@ -291,3 +290,31 @@
         settings = get_global_registry().settings
         terms = [SimpleTerm(name, title=name) for name, uri in get_uris(settings)]
         super(ZODBConnectionVocabulary, self).__init__(terms)
+
+
+volatile_marker = object()
+
+
+class volatile_property:
+    """Property decorator to define volatile attributes into persistent classes"""
+
+    def __init__(self, fget, doc=None):
+        self.fget = fget
+        self.__doc__ = doc or fget.__doc__
+        self.__name__ = fget.__name__
+        self.__module__ = fget.__module__
+
+    def __get__(self, inst, cls):
+        if inst is None:
+            return self
+        attrname = '_v_{0}'.format(self.__name__)
+        value = getattr(inst, attrname, volatile_marker)
+        if value is volatile_marker:
+            value = self.fget(inst)
+            setattr(inst, attrname, value)
+        return value
+
+    def __delete__(self, inst):
+        attrname = '_v_{0}'.format(self.__name__)
+        if hasattr(inst, attrname):
+            delattr(inst, attrname)