changeset 77:4282391dd693

util: add propertycache decorator
author Idan Kamara <idankk86@gmail.com>
date Sat, 15 Oct 2011 21:47:15 +0200
parents 37307caccf54
children 031cbb8d4f65
files hglib/util.py
diffstat 1 files changed, 24 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/hglib/util.py	Sat Oct 15 20:09:59 2011 +0200
+++ b/hglib/util.py	Sat Oct 15 21:47:15 2011 +0200
@@ -131,6 +131,30 @@
         """ Returns True if the return code was 0, False otherwise """
         return self.ret == 0
 
+class propertycache(object):
+    """
+    Decorator that remembers the return value of a function call.
+
+    >>> class obj(object):
+    ...     def func(self):
+    ...         print 'func'
+    ...         return []
+    ...     func = propertycache(func)
+    >>> o = obj()
+    >>> o.func
+    func
+    []
+    >>> o.func
+    []
+    """
+    def __init__(self, func):
+        self.func = func
+        self.name = func.__name__
+    def __get__(self, obj, type=None):
+        result = self.func(obj)
+        setattr(obj, self.name, result)
+        return result
+
 close_fds = os.name == 'posix'
 
 startupinfo = None