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
|
# Copyright: 2005 Gentoo Foundation
# Author(s): Brian Harring (ferringb@gentoo.org)
# License: GPL2
# $Id$
import sys
import warnings
import weakref
class Mapping(object):
"""
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:
http://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.
"""
def __iter__(self):
return self.iterkeys()
def keys(self):
return list(self.__iter__())
def has_key(self, key):
warnings.warn("portage.cache.mappings.Mapping.has_key() " + \
"is deprecated, use the in operator instead", DeprecationWarning)
return key in self
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.iteritems():
yield v
def values(self):
return [v for _, v in self.iteritems()]
def items(self):
return list(self.iteritems())
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def __repr__(self):
return repr(dict(self.iteritems()))
def __len__(self):
return len(self.keys())
if sys.hexversion >= 0x3000000:
items = iteritems
keys = __iter__
values = itervalues
class MutableMapping(Mapping):
"""
A mutable vesion of the Mapping class.
"""
def clear(self):
for key in self.keys():
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 = self.iteritems().next()
except StopIteration:
raise KeyError('container is empty')
del self[k]
return (k, v)
def update(self, other=None, **kwargs):
if other is None:
pass
elif hasattr(other, 'iteritems'):
for k, v in other.iteritems():
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 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.iterkeys():
yield k
for k in self.orig.iterkeys():
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)
def has_key(self, key):
warnings.warn("portage.cache.mapping.ProtectedDict.has_key() is"
" deprecated, use the in operator instead",
DeprecationWarning)
return key in self
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]
elif 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 has_key(self, key):
warnings.warn("portage.cache.mappings.LazyLoad.has_key() is "
"deprecated, use the in operator instead",
DeprecationWarning)
return key in self
def __contains__(self, key):
if key in self.d:
return True
elif self.pull != None:
self.d.update(self.pull())
self.pull = None
return key in self.d
_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
@returns: 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(object):
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 keys(self):
return list(self)
def iteritems(self):
for k in self.allowed_keys:
try:
yield (k, getattr(self, self._prefix + k))
except AttributeError:
pass
def items(self):
return list(self.iteritems())
def itervalues(self):
for k, v in self.iteritems():
yield v
def values(self):
return list(self.itervalues())
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, d):
i = getattr(d, "iteritems", None)
if i is None:
i = d
else:
i = i()
for k, v in i:
self[k] = v
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 has_key(self, k):
warnings.warn("portage.cache.mappings.SlotDict.has_key()" + \
" is deprecated, use the in operator instead",
DeprecationWarning)
return k in self
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()))
if sys.hexversion >= 0x3000000:
items = iteritems
keys = __iter__
values = itervalues
v = SlotDict
_slot_dict_classes[v.allowed_keys] = v
return v
|