b5efab2d400698c4c71672520245baaa671533b6
[p2pool.git] / p2pool / util / memoize.py
1 _nothing = object()
2
3 def memoize_with_backing(backing, has_inverses=set()):
4     def a(f):
5         def b(*args):
6             res = backing.get((f, args), _nothing)
7             if res is not _nothing:
8                 return res
9             
10             res = f(*args)
11             
12             backing[(f, args)] = res
13             for inverse in has_inverses:
14                 backing[(inverse, args[:-1] + (res,))] = args[-1]
15             
16             return res
17         return b
18     return a
19
20 def memoize(f):
21     return memoize_with_backing({})(f)