Bug 1047267 - Add a memoize decorator to the mozbuild module. r=gps

This commit is contained in:
Mike Hommey 2014-08-07 14:20:37 +09:00
parent 9be788de2f
commit e426d85e54
2 changed files with 35 additions and 0 deletions

View File

@ -20,6 +20,7 @@ from mozunit import (
from mozbuild.util import (
FileAvoidWrite,
hash_file,
memoize,
resolve_target_to_make,
MozbuildDeletionError,
HierarchicalStringList,
@ -429,5 +430,27 @@ class TestHierarchicalStringListWithFlagsFactory(unittest.TestCase):
l.x['y'].baz = False
class TestMemoize(unittest.TestCase):
def test_memoize(self):
self._count = 0
@memoize
def wrapped(a, b):
self._count += 1
return a + b
self.assertEqual(wrapped(1, 1), 2)
self.assertEqual(self._count, 1)
self.assertEqual(wrapped(1, 1), 2)
self.assertEqual(self._count, 1)
self.assertEqual(wrapped(2, 1), 3)
self.assertEqual(self._count, 2)
self.assertEqual(wrapped(1, 2), 3)
self.assertEqual(self._count, 3)
self.assertEqual(wrapped(1, 2), 3)
self.assertEqual(self._count, 3)
self.assertEqual(wrapped(1, 1), 2)
self.assertEqual(self._count, 3)
if __name__ == '__main__':
main()

View File

@ -20,6 +20,7 @@ from collections import (
defaultdict,
OrderedDict,
)
from functools import wraps
from StringIO import StringIO
@ -706,3 +707,14 @@ class OrderedDefaultDict(OrderedDict):
except KeyError:
value = self[key] = self._default_factory()
return value
def memoize(func):
cache = {}
@wraps(func)
def wrapper(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrapper