import, naming, whitespace cleanup
[p2pool.git] / p2pool / util / memoize.py
1 _nothing = object()
2
3 def memoize_with_backing(backing, inverse_of=None):
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             if inverse_of is not None:
14                 if len(args) != 1:
15                     raise ValueError('inverse_of can only be used for functions taking one argument')
16                 backing[(inverse_of, (res,))] = args[0]
17             
18             return res
19         return b
20     return a
21
22 def memoize(f):
23     return memoize_with_backing({})(f)