2to3 (compiles, not tested)
[tag_parser.git] / src / mjacob / annotations / memoized.py
blob0fb5e8c6093386b8a108450bc3cbe1a2538878f3
1 # This Python file uses the following encoding: utf-8
2 '''
3 Created on May 12, 2011
5 a simple memoization routine
7 @author: mjacob
8 '''
10 def Memoize(func):
11 """replace an function without arguments with a function that merely returns the result"""
12 def f1(selv):
13 value = func(selv)
14 def f2():
15 return value
16 setattr(selv, func.__name__, f2)
17 return value
18 return f1
20 if __name__ == "__main__":
21 """test functionality"""
22 class foobar(object):
23 def __init__(self, v):
24 self.__v = v
26 @Memoize
27 def thing(self):
28 print("computing %s" % (self.__v))
29 return 100*self.__v
31 a = foobar(1)
32 b = foobar(2)
33 print("starting")
34 print(a.thing)
35 print(a.thing())
36 print(a.thing)
37 print(a.thing())
38 print(a.thing)
39 print(b.thing())
40 print(b.thing())