memoize.py 6.26 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python
#
# memoize.py - Memoization decorators.
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
"""This module provides a handful of decorators which may be used to memoize
a function:

 .. autosummary::
    :nosignatures:

13
    Instanceify
14
    memoizeMD5
15
    skipUnchanged
16
17
"""

18

19
20
import logging

21
import hashlib
22
import functools
Paul McCarthy's avatar
Paul McCarthy committed
23
import six
24

25
26
log = logging.getLogger(__name__)

27

28
29
# TODO Make this a class, and add
#      a "clearCache" method to it.
30
def memoize(func):
31
32
33
34
35
    """Memoize the given function by the value of the input arguments, allowing
    the caller to specify which positional arguments (by index) and keyword
    arguments (by name) are used for the comparison.

    If no positional or keyword arguments are specified, the function is
36
    memoized on all arguments. Note that the arguments used for memoization
Paul McCarthy's avatar
Paul McCarthy committed
37
38
    must be hashable, as they are used as keys in a dictionary.

39
40
41
42
43

    :arg args:   A list of positional argument indices.
    :arg kwargs: A list of keyword argument names.
    """

44
45
    cache      = {}
    defaultKey = '_memoize_noargs_'
46

47
    def wrapper(*a, **kwa):
48

49
        key = []
50

51
52
        if a   is not None: key += list(a)
        if kwa is not None: key += [kwa[k] for k in sorted(kwa.keys())]
53

54
55
56
57
58
        # This decorator was created without
        # any arguments specified - use the
        # default cache key.
        if len(key) == 0:
            key = [defaultKey]
59

60
61
62
63
        key = tuple(key)
        
        try:
            result = cache[key]
64

65
        except KeyError:
66

67
68
            result     = func(*a, **kwa)
            cache[key] = result
69

70
            log.debug('Adding to cache[{}]: {}'.format(key, result))
71

72
73
        return result
    return wrapper
74
75


76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def memoizeMD5(func):
    """Memoize the given function. Whenever the function is called, an
    md5 digest of its arguments is calculated - if the digest has been
    previously cached, the previous value calculated by the function is
    returned.
    """

    cache = {}

    def wrapper(*args, **kwargs):
        args = list(args) + list(kwargs.values())

        hashobj = hashlib.md5()

        for arg in args:
91
            arg = six.u(str(arg)).encode('utf-8')
Paul McCarthy's avatar
Paul McCarthy committed
92
            hashobj.update(arg)
93
94
95
96
97
98
99
100
101

        digest = hashobj.hexdigest()
        cached = cache.get(digest)

        if cached is not None:
            return cached

        result = func(*args, **kwargs)

102
103
104
        log.debug('Adding to MD5 cache[{}]: {}'.format(
            digest, result))

105
106
107
108
109
        cache[digest] = result

        return result

    return wrapper
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179


def skipUnchanged(func):
    """This decorator is intended for use with *setter* functions - a function
     which accepts a name and a value, and is intended to set some named
     attribute to the given value.

    This decorator keeps a cache of name-value pairs. When the decorator is
    called with a specific name and value, the cache is checked and, if the
    given value is the same as the cached value, the decorated function is
    *not* called. If the given value is different from the cached value (or
    there is no value), the decorated function is called.

    .. note:: This decorator ignores the return value of the decorated
              function.

    :returns: ``True`` if the underlying setter function was called, ``False``
              otherwise.
    """

    import numpy as np
    
    cache = {}
    
    def wrapper(name, value, *args, **kwargs):

        oldVal = cache.get(name, None)

        if oldVal is not None:
            
            oldIsArray = isinstance(oldVal, np.ndarray)
            newIsArray = isinstance(value,  np.ndarray)
            isarray    = oldIsArray or newIsArray

            if isarray: nochange = np.all(oldVal == value)
            else:       nochange =        oldVal == value

            if nochange:
                return False 

        func(name, value, *args, **kwargs)

        cache[name] = value

        return True

    return wrapper


class Instanceify(object):
    """This class is intended to be used to decorate other decorators, so they
    can be applied to instance methods. For example, say we have the following
    class::

        class Container(object):

            def __init__(self):
                self.__items = {}

            @skipUnchanged
            def set(self, name, value):
                self.__items[name] = value

    
    Given this definition, a single :func:`skipUnchanged` decorator will be
    created and shared amongst all ``Container`` instances. This is not ideal,
    as the value cache created by the :func:`skipUnchanged` decorator should
    be associated with a single ``Container`` instance.

    
180
    By redefining the ``Container`` class definition like so::
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235

    
        class Container(object):

            def __init__(self):
                self.__items = {}

            @Instanceify(skipUnchanged)
            def set(self, name, value):
                self.__items[name] = value


    a separate :func:`skipUnchanged` decorator is created for, and associated
    with, every ``Container`` instance.

    
    This is achieved because an ``Instanceify`` instance is a descriptor. When
    first accessed as an instance attribute, an ``Instanceify`` instance will
    create the real decorator function, and replace itself on the instance.
    """

    
    def __init__(self, realDecorator):
        """Create an ``Instanceify`` decorator.

        :arg realDecorator: A reference to the decorator that is to be
                            *instance-ified*.
        """

        self.__realDecorator = realDecorator
        self.__func          = None


    def __call__(self, func):
        """Called immediately after :meth:`__init__`, and passed the method
        that is to be decorated.
        """
        self.__func = func
        return self


    def __get__(self, instance, cls):
        """When an ``Instanceify`` instance is accessed as an attribute of
        another object, it will create the real (instance-ified) decorator,
        and replace itself on the instance with the real decorator.
        """

        if instance is None:
            return self.__func

        method    = functools.partial(self.__func, instance)
        decMethod = self.__realDecorator(method)

        setattr(instance, self.__func.__name__, decMethod)
        return functools.update_wrapper(decMethod, self.__func)