|
1 from django.core.cache import cache |
|
2 |
|
3 # adapted [to django] from http://code.activestate.com/recipes/325205/ |
|
4 def dj_memoize(f): |
|
5 def g(*args, **kwargs): |
|
6 key = ( f.__name__, f, tuple(args), frozenset(kwargs.items()) ) |
|
7 val = cache.get(key) |
|
8 if not val: |
|
9 val = f(*args, **kwargs) |
|
10 cache.set(key,val) |
|
11 return val |
|
12 return g |
|
13 |
|
14 |
|
15 |
|
16 # adapted from http://code.activestate.com/recipes/496879/ |
|
17 # decorator with LRU policy |
|
18 |
|
19 # changed : |
|
20 # - default limit is 100 |
|
21 # - store sha1 of key (shorter) |
|
22 import cPickle, hashlib |
|
23 |
|
24 def memoize(function, limit=100): |
|
25 if isinstance(function, int): |
|
26 def memoize_wrapper(f): |
|
27 return memoize(f, function) |
|
28 |
|
29 return memoize_wrapper |
|
30 |
|
31 dict = {} |
|
32 list = [] |
|
33 def memoize_wrapper(*args, **kwargs): |
|
34 key = hashlib.sha1(cPickle.dumps((args, kwargs))).digest() |
|
35 try: |
|
36 list.append(list.pop(list.index(key))) |
|
37 except ValueError: |
|
38 dict[key] = function(*args, **kwargs) |
|
39 list.append(key) |
|
40 if limit is not None and len(list) > limit: |
|
41 del dict[list.pop(0)] |
|
42 |
|
43 return dict[key] |
|
44 |
|
45 memoize_wrapper._memoize_dict = dict |
|
46 memoize_wrapper._memoize_list = list |
|
47 memoize_wrapper._memoize_limit = limit |
|
48 memoize_wrapper._memoize_origfunc = function |
|
49 memoize_wrapper.func_name = function.func_name |
|
50 return memoize_wrapper |