[PATCH 1 of 3 hglib] util: add propertycache decorator

Idan Kamara idankk86 at gmail.com
Sat Oct 15 14:47:45 CDT 2011


# HG changeset patch
# User Idan Kamara <idankk86 at gmail.com>
# Date 1318708035 -7200
# Node ID 5574413bce099f120fbf1ada7af59853c69f78db
# Parent  5cf6af9a9411c52bb13e13738f35e82e556f1c6b
util: add propertycache decorator

diff --git a/hglib/util.py b/hglib/util.py
--- a/hglib/util.py
+++ b/hglib/util.py
@@ -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


More information about the Mercurial-devel mailing list