Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | 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
                print "HIT"
25
                if now - last_update > self.ttl:
26
                    print "EXPIRED"
27
                    raise AttributeError
28
            except (KeyError, AttributeError):
29
                print "MISS"
30
                value = func(*args)
31
                self.cache[args] = value, now
32
            except TypeError:
33
                print "MISS"
34
                return func(*args)
35
            return value
36
        return wrapped_function
37
 
38
    def __repr__(self):
39
        return self.func.__doc__
40
 
41
'''
42
Example usage
43
'''
44
 
45
@memoized(0)
46
def fibonacci(n):
47
    if n <= 1:
48
        return n
49
    return fibonacci(n-2) + fibonacci(n-1)
50
 
51
def main():
52
    print fibonacci(10)
53
    print fibonacci(12)
54
if __name__ == '__main__':
55
    main()