aboutsummaryrefslogtreecommitdiff
blob: c0f2147a9772397b1b6fac1c486f1326917dba72 (plain)
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
38
39
40
41
42
43
44
45
46
47
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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
180
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# Copyright: 2005-2020 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
# Author(s): Brian Harring (ferringb@gentoo.org)

__all__ = [
    "Mapping",
    "MutableMapping",
    "UserDict",
    "ProtectedDict",
    "LazyLoad",
    "slot_dict_class",
]

import weakref


class Mapping:
    """
    In python-3.0, the UserDict.DictMixin class has been replaced by
    Mapping and MutableMapping from the collections module, but 2to3
    doesn't currently account for this change:

        https://bugs.python.org/issue2876

    As a workaround for the above issue, use this class as a substitute
    for UserDict.DictMixin so that code converted via 2to3 will run.
    """

    __slots__ = ()

    def __iter__(self):
        return iter(self.keys())

    def __contains__(self, key):
        try:
            value = self[key]
        except KeyError:
            return False
        return True

    def iteritems(self):
        for k in self:
            yield (k, self[k])

    def iterkeys(self):
        return self.__iter__()

    def itervalues(self):
        for _, v in self.items():
            yield v

    def get(self, key, default=None):
        try:
            return self[key]
        except KeyError:
            return default

    def __repr__(self):
        return repr(dict(self.items()))

    def __len__(self):
        return len(list(self))

    # TODO: do we need to keep iter*?
    items = iteritems
    keys = __iter__
    values = itervalues


class MutableMapping(Mapping):
    """
    A mutable vesion of the Mapping class.
    """

    __slots__ = ()

    def clear(self):
        for key in list(self):
            del self[key]

    def setdefault(self, key, default=None):
        try:
            return self[key]
        except KeyError:
            self[key] = default
        return default

    def pop(self, key, *args):
        if len(args) > 1:
            raise TypeError(
                "pop expected at most 2 arguments, got " + repr(1 + len(args))
            )
        try:
            value = self[key]
        except KeyError:
            if args:
                return args[0]
            raise
        del self[key]
        return value

    def popitem(self):
        try:
            k, v = next(iter(self.items()))
        except StopIteration:
            raise KeyError("container is empty")
        del self[k]
        return (k, v)

    def update(self, *args, **kwargs):
        if len(args) > 1:
            raise TypeError(
                "expected at most 1 positional argument, got " + repr(len(args))
            )
        other = None
        if args:
            other = args[0]
        if other is None:
            pass
        elif hasattr(other, "iteritems"):
            # Use getattr to avoid interference from 2to3.
            for k, v in getattr(other, "iteritems")():
                self[k] = v
        elif hasattr(other, "items"):
            # Use getattr to avoid interference from 2to3.
            for k, v in getattr(other, "items")():
                self[k] = v
        elif hasattr(other, "keys"):
            for k in other.keys():
                self[k] = other[k]
        else:
            for k, v in other:
                self[k] = v
        if kwargs:
            self.update(kwargs)


class UserDict(MutableMapping):
    """
    Use this class as a substitute for UserDict.UserDict so that
    code converted via 2to3 will run:

         https://bugs.python.org/issue2876
    """

    __slots__ = ("data",)

    def __init__(self, *args, **kwargs):

        self.data = {}

        if len(args) > 1:
            raise TypeError(
                "expected at most 1 positional argument, got " + repr(len(args))
            )

        if args:
            self.update(args[0])

        if kwargs:
            self.update(kwargs)

    def __repr__(self):
        return repr(self.data)

    def __contains__(self, key):
        return key in self.data

    def __iter__(self):
        return iter(self.data)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, key):
        return self.data[key]

    def __setitem__(self, key, item):
        self.data[key] = item

    def __delitem__(self, key):
        del self.data[key]

    def clear(self):
        self.data.clear()

    keys = __iter__


class ProtectedDict(MutableMapping):
    """
    given an initial dict, this wraps that dict storing changes in a secondary dict, protecting
    the underlying dict from changes
    """

    __slots__ = ("orig", "new", "blacklist")

    def __init__(self, orig):
        self.orig = orig
        self.new = {}
        self.blacklist = {}

    def __setitem__(self, key, val):
        self.new[key] = val
        if key in self.blacklist:
            del self.blacklist[key]

    def __getitem__(self, key):
        if key in self.new:
            return self.new[key]
        if key in self.blacklist:
            raise KeyError(key)
        return self.orig[key]

    def __delitem__(self, key):
        if key in self.new:
            del self.new[key]
        elif key in self.orig:
            if key not in self.blacklist:
                self.blacklist[key] = True
                return
        raise KeyError(key)

    def __iter__(self):
        for k in self.new:
            yield k
        for k in self.orig:
            if k not in self.blacklist and k not in self.new:
                yield k

    def __contains__(self, key):
        return key in self.new or (key not in self.blacklist and key in self.orig)

    keys = __iter__


class LazyLoad(Mapping):
    """
    Lazy loading of values for a dict
    """

    __slots__ = ("pull", "d")

    def __init__(self, pull_items_func, initial_items=[]):
        self.d = {}
        for k, v in initial_items:
            self.d[k] = v
        self.pull = pull_items_func

    def __getitem__(self, key):
        if key in self.d:
            return self.d[key]
        if self.pull != None:
            self.d.update(self.pull())
            self.pull = None
        return self.d[key]

    def __iter__(self):
        if self.pull is not None:
            self.d.update(self.pull())
            self.pull = None
        return iter(self.d)

    def __contains__(self, key):
        if key in self.d:
            return True
        if self.pull != None:
            self.d.update(self.pull())
            self.pull = None
        return key in self.d

    keys = __iter__


_slot_dict_classes = weakref.WeakValueDictionary()


def slot_dict_class(keys, prefix="_val_"):
    """
    Generates mapping classes that behave similar to a dict but store values
    as object attributes that are allocated via __slots__. Instances of these
    objects have a smaller memory footprint than a normal dict object.

    @param keys: Fixed set of allowed keys
    @type keys: Iterable
    @param prefix: a prefix to use when mapping
            attribute names from keys
    @type prefix: String
    @rtype: SlotDict
    @return: A class that constructs SlotDict instances
            having the specified keys.
    """
    if isinstance(keys, frozenset):
        keys_set = keys
    else:
        keys_set = frozenset(keys)
    v = _slot_dict_classes.get((keys_set, prefix))
    if v is None:

        class SlotDict:

            allowed_keys = keys_set
            _prefix = prefix
            __slots__ = ("__weakref__",) + tuple(prefix + k for k in allowed_keys)

            def __init__(self, *args, **kwargs):

                if len(args) > 1:
                    raise TypeError(
                        "expected at most 1 positional argument, got " + repr(len(args))
                    )

                if args:
                    self.update(args[0])

                if kwargs:
                    self.update(kwargs)

            def __iter__(self):
                for k, v in self.iteritems():
                    yield k

            def __len__(self):
                l = 0
                for i in self.iteritems():
                    l += 1
                return l

            def iteritems(self):
                prefix = self._prefix
                for k in self.allowed_keys:
                    try:
                        yield (k, getattr(self, prefix + k))
                    except AttributeError:
                        pass

            def itervalues(self):
                for k, v in self.iteritems():
                    yield v

            def __delitem__(self, k):
                try:
                    delattr(self, self._prefix + k)
                except AttributeError:
                    raise KeyError(k)

            def __setitem__(self, k, v):
                setattr(self, self._prefix + k, v)

            def setdefault(self, key, default=None):
                try:
                    return self[key]
                except KeyError:
                    self[key] = default
                return default

            def update(self, *args, **kwargs):
                if len(args) > 1:
                    raise TypeError(
                        "expected at most 1 positional argument, got " + repr(len(args))
                    )
                other = None
                if args:
                    other = args[0]
                if other is None:
                    pass
                elif hasattr(other, "iteritems"):
                    # Use getattr to avoid interference from 2to3.
                    for k, v in getattr(other, "iteritems")():
                        self[k] = v
                elif hasattr(other, "items"):
                    # Use getattr to avoid interference from 2to3.
                    for k, v in getattr(other, "items")():
                        self[k] = v
                elif hasattr(other, "keys"):
                    for k in other.keys():
                        self[k] = other[k]
                else:
                    for k, v in other:
                        self[k] = v
                if kwargs:
                    self.update(kwargs)

            def __getitem__(self, k):
                try:
                    return getattr(self, self._prefix + k)
                except AttributeError:
                    raise KeyError(k)

            def get(self, key, default=None):
                try:
                    return self[key]
                except KeyError:
                    return default

            def __contains__(self, k):
                return hasattr(self, self._prefix + k)

            def pop(self, key, *args):
                if len(args) > 1:
                    raise TypeError(
                        "pop expected at most 2 arguments, got " + repr(1 + len(args))
                    )
                try:
                    value = self[key]
                except KeyError:
                    if args:
                        return args[0]
                    raise
                del self[key]
                return value

            def popitem(self):
                try:
                    k, v = self.iteritems().next()
                except StopIteration:
                    raise KeyError("container is empty")
                del self[k]
                return (k, v)

            def copy(self):
                c = self.__class__()
                c.update(self)
                return c

            def clear(self):
                for k in self.allowed_keys:
                    try:
                        delattr(self, self._prefix + k)
                    except AttributeError:
                        pass

            def __str__(self):
                return str(dict(self.iteritems()))

            def __repr__(self):
                return repr(dict(self.iteritems()))

            items = iteritems
            keys = __iter__
            values = itervalues

        v = SlotDict
        _slot_dict_classes[v.allowed_keys] = v
    return v