|
Package memtools ::
Module pattern
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 from functools import wraps
38 from hashlib import md5
39 import logging
40
42 """ This class wraps a normal callable and returns a memorized callable
43 with a "memo" storage. End users are not intended to know what happens
44 inside this class, neither they should know about it.
45
46 """
47
48 - def __init__(self, f, memo, hashing_function=md5, debug=False):
49 self.__f = f
50 self.__memo = memo
51 logging.basicConfig(level=logging.WARNING)
52 self.log = logging.getLogger("Memorized Callable %s" % f.__name__)
53 if debug:
54 self.log.setLevel(logging.DEBUG)
55 self.hashing_function = hashing_function
56
58
59 the_hash = self.hashing_function(f.__name__)
60 for arg in args:
61 the_hash.update(str(arg))
62 the_hash.update("|")
63 for key, val in kwargs.iteritems():
64 the_hash.update("%s:%s;".__mod__(key, val))
65 return the_hash.hexdigest()
66
68 key = self.__create_key(self.__f, args, kwargs)
69 self.log.debug("Calling memorized value %s", key)
70 try:
71 return self.__memo[key]
72 except KeyError:
73 self.log.debug("No key %s found. Calculating value...", key)
74 val = self.__f(*args, **kwargs)
75 self.__memo[key] = val
76 return val
77
78
80 """
81 The memorize decorator takes a Memory (or Memory-compatible) object
82 and masks the Memorized decorator to keep the original signature
83 clean.
84
85 Use of this decorator is deprecated since Memory objects implement
86 the same functionality in their __call__ methods.
87 """
88
89 - def __init__(self, memory, debug=False):
90 self._memory = memory
91 self.debug = debug
92
94 memo = Memorized(f, self._memory, self.debug)
95 wraps(f)(memo)
96 return memo
97