Add cachefunc to abstract function call cache
authorBrendan Cully <brendan@kublai.com>
Fri, 22 Sep 2006 08:19:25 -0700
changeset 3145 e4ea47c21480
parent 3144 8342ad5abe0b
child 3146 e69a0cbe268e
Add cachefunc to abstract function call cache
mercurial/util.py
--- a/mercurial/util.py	Fri Sep 22 08:19:25 2006 -0700
+++ b/mercurial/util.py	Fri Sep 22 08:19:25 2006 -0700
@@ -24,6 +24,22 @@
 class SignalInterrupt(Exception):
     """Exception raised on SIGTERM and SIGHUP."""
 
+def cachefunc(func):
+    '''cache the result of function calls'''
+    cache = {}
+    if func.func_code.co_argcount == 1:
+        def f(arg):
+            if arg not in cache:
+                cache[arg] = func(arg)
+            return cache[arg]
+    else:
+        def f(*args):
+            if args not in cache:
+                cache[args] = func(*args)
+            return cache[args]
+
+    return f
+
 def pipefilter(s, cmd):
     '''filter string S through command CMD, returning its output'''
     (pout, pin) = popen2.popen2(cmd, -1, 'b')