memoize.py 6.5 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
import hashlib
20
import functools
Paul McCarthy's avatar
Paul McCarthy committed
21
import six
22
23


24
25
# TODO Make this a class, and add
#      a "clearCache" method to it.
26
27
28
29
30
31
def memoize(args=None, kwargs=None):
    """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
32
33
    memoized on all arguments. Note that the arguments used for memoization
    must be hashable, as they are used as keys in a dictionary..
34
35
36
37
38
39
40
41
42
43
44

    .. note:: This decorator must always be called with brackets, e.g.::
                  memoize()
                  def myfunc():
                      ...

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

    def decorator(func):
45
46
47

        cache = {}
 
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        def wrapper(*a, **kwa):

            key = []

            if args   is not None: key += [a[  i] for i in args]
            if kwargs is not None: key += [kwa[k] for k in kwargs]

            # This decorator was created without
            # any arguments specified - use all
            # the arguments as the cache key.
            if len(key) == 0:

                # Keyword arguments are unordered,
                # so we'll try and overcome this
                # by sorting the kwarg dict keys.
                key = list(a) + list([kwa[k] for k in sorted(kwa.keys)])

            key = tuple(key)

            try:
                result = cache[key]

            except KeyError:

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

            return result
        return wrapper

    return decorator


81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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:
Paul McCarthy's avatar
Paul McCarthy committed
96
97
            arg = six.u(arg).encode('utf-8')
            hashobj.update(arg)
98
99
100
101
102
103
104
105
106
107
108
109
110
111

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

        if cached is not None:
            return cached

        result = func(*args, **kwargs)

        cache[digest] = result

        return result

    return wrapper
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
180
181


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.

    
182
    By redefining the ``Container`` class definition like so::
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
236
237

    
        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)