Subversion Repositories SmartDukaan

Rev

Rev 3098 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3098 rajveer 1
'''
2
Created on 30-Aug-2011
3
 
4
@author: rajveer
5
'''
6
 
7
import time
8
class memoized(object):
9
    '''
10
    Simple caching for function returns. 
11
    Any function return can be memoized for a given time duration.
12
    Time to live also need to be mentioned. It is represented as number of seconds
13
    '''
14
 
15
    def __init__(self, ttl):
16
        self.cache = {}
17
        self.ttl = ttl
18
 
19
    def __call__(self, func):
20
        def wrapped_function(*args):
21
            try:
22
                now = time.time()
23
                value, last_update = self.cache[args]
24
                if now - last_update > self.ttl:
25
                    print "EXPIRED"
26
                    raise AttributeError
3148 rajveer 27
                print "HIT"
28
            except KeyError:
3098 rajveer 29
                print "MISS"
30
                value = func(*args)
31
                self.cache[args] = value, now
3148 rajveer 32
            except AttributeError:
33
                value = func(*args)
34
                self.cache[args] = value, now
3098 rajveer 35
            except TypeError:
36
                print "MISS"
37
                return func(*args)
38
            return value
39
        return wrapped_function
40
 
41
    def __repr__(self):
42
        return self.func.__doc__
43
 
44
'''
45
Example usage
46
'''
47
 
48
@memoized(0)
49
def fibonacci(n):
50
    if n <= 1:
51
        return n
52
    return fibonacci(n-2) + fibonacci(n-1)
53
 
54
def main():
55
    print fibonacci(10)
56
    print fibonacci(12)
57
if __name__ == '__main__':
58
    main()