Debian Codegraph @

collections_extended/indexed_dict.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """IndexedDict class definition.
2
3 .. versionadded:: 1.0.3
4 """
5 from collections.abc import MutableMapping
6
7 from ._util import deprecation_warning
8 from .sentinel import NOT_SET
9
10 __all__ = ('IndexedDict', )
11
12 # TODO these should be ValueErrors
13 KEY_AND_INDEX_ERROR = TypeError(
14 "Specifying both `key` and `index` is not allowed")
15 KEY_EQ_INDEX_ERROR = TypeError(
16 "Exactly one of `key` and `index` must be specified")
17
18
19 class IndexedDict(MutableMapping):
20 """A Mapping that preserves insertion order and allows access by item index.
21
22 The API is an extension of OrderedDict.
23 """
24
25 def __init__(self, iterable=None, **kwargs):
26 """Create an IndexedDict and initialize it like a dict."""
27 self._dict = {} # key -> (index, value)
28 self._list = [] # index -> (key, value)
29 self.update(iterable or [], **kwargs)
30
31 def clear(self):
32 """Remove all items."""
33 self._dict = {}
34 self._list = []
35
36 def get(self, key=NOT_SET, index=NOT_SET, default=NOT_SET, d=NOT_SET):
37 """Return value with given `key` or `index`.
38
39 If no value is found, return `default` (`None` by default).
40
41 .. deprecated :: 1.0.3
42
43 The `d` parameter has been renamed `default`. `d` will be removed in
44 some future version.
45
46 Args:
47 key: The key of the value to get
48 index: The index of the value to get
49 default: The value to return if `key` is not found or `index` is
50 out of bounds. If it is NOT_SET, None is returned.
51 d: DEPRECATED: Old parameter name for `default`
52
53 """
54 if d is not NOT_SET:
55 if default is not NOT_SET:
56 raise ValueError('Specified default and d')
57 deprecation_warning(
58 "IndexedDict.pop parameter 'd' has been renamed to 'default'"
59 )
60 default = d
61 if default is NOT_SET:
62 default = None
63
64 if index is NOT_SET and key is not NOT_SET:
65 try:
66 index, value = self._dict[key]
67 except KeyError:
68 return default
69 else:
70 return value
71 elif index is not NOT_SET and key is NOT_SET:
72 try:
73 key, value = self._list[index]
74 except IndexError:
75 return default
76 else:
77 return value
78 else:
79 raise KEY_EQ_INDEX_ERROR
80
81 def pop(self, key=NOT_SET, index=NOT_SET, default=NOT_SET, d=NOT_SET):
82 """Remove and return value.
83
84 Optionally, specify the `key` or `index` of the value to pop.
85 If `key` is specified and is not found a `KeyError` is raised unless
86 `default` is specified. Likewise, if `index` is specified that is out of
87 bounds, an `IndexError` is raised unless `default` is specified.
88
89 Both `index` and `key` cannot be specified. If neither is specified,
90 then the last value is popped.
91
92 This is generally O(N) unless removing last item, then O(1).
93
94 .. deprecated :: 1.0.3
95
96 The `d` parameter has been renamed `default`. `d` will be removed in
97 some future version.
98
99 Args:
100 key: The key of the value to pop
101 index: The index of the value to pop
102 default: The value to return if the key is not found or the index is
103 out of bounds
104 d: DEPRECATED: Old parameter name for `default`
105
106 """
107 if d is not NOT_SET:
108 if default is not NOT_SET:
109 raise ValueError('Specified default and d')
110 deprecation_warning(
111 "IndexedDict.pop parameter 'd' has been renamed to 'default'"
112 )
113 default = d
114
115 has_default = default is not NOT_SET
116 if index is NOT_SET and key is not NOT_SET:
117 index, value = self._pop_key(key, has_default)
118 elif key is NOT_SET:
119 key, index, value = self._pop_index(index, has_default)
120 else:
121 raise KEY_AND_INDEX_ERROR
122
123 if index is None:
124 return default
125 else:
126 self._fix_indices_after_delete(index)
127 return value
128
129 def _pop_key(self, key, has_default):
130 """Remove an element by key."""
131 try:
132 index, value = self._dict.pop(key)
133 except KeyError:
134 if has_default:
135 return None, None
136 else:
137 raise
138 key2, value2 = self._list.pop(index)
139 assert key is key2
140 assert value is value2
141
142 return index, value
143
144 def _pop_index(self, index, has_default):
145 """Remove an element by index, or last element."""
146 try:
147 if index is NOT_SET:
148 index = len(self._list) - 1
149 key, value = self._list.pop()
150 else:
151 key, value = self._list.pop(index)
152 if index < 0:
153 index += len(self._list) + 1
154 except IndexError:
155 if has_default:
156 return None, None, None
157 else:
158 raise
159 index2, value2 = self._dict.pop(key)
160 assert index == index2
161 assert value is value2
162
163 return key, index, value
164
165 def fast_pop(self, key=NOT_SET, index=NOT_SET):
166 """Pop a specific item quickly by swapping it to the end.
167
168 Remove value with given key or index (last item by default) fast
169 by swapping it to the last place first.
170
171 Changes order of the remaining items (item that used to be last goes to
172 the popped location).
173 Returns tuple of (poped_value, new_moved_index, moved_key, moved_value).
174 If key is not found raises KeyError or IndexError.
175
176 Runs in O(1).
177 """
178 if index is NOT_SET and key is not NOT_SET:
179 index, popped_value = self._dict.pop(key)
180 elif key is NOT_SET:
181 if index is NOT_SET:
182 index = len(self._list) - 1
183 key, popped_value2 = self._list[-1]
184 else:
185 key, popped_value2 = self._list[index]
186 if index < 0:
187 index += len(self._list)
188 index2, popped_value = self._dict.pop(key)
189 assert index == index2
190 else:
191 raise KEY_AND_INDEX_ERROR
192
193 if key == self._list[-1][0]:
194 # The item we're removing happens to be the last in the list,
195 # no swapping needed
196 _, popped_value2 = self._list.pop()
197 assert popped_value is popped_value2
198 return popped_value, len(self._list), key, popped_value
199 else:
200 # Swap the last item onto the deleted spot and
201 # pop the last item from the list
202 self._list[index] = self._list[-1]
203 moved_key, moved_value = self._list.pop()
204 self._dict[moved_key] = (index, moved_value)
205 return popped_value, index, moved_key, moved_value
206
207 def popitem(self, last=NOT_SET, *, key=NOT_SET, index=NOT_SET):
208 """Remove and return a (key, value) tuple.
209
210 By default, the last item is popped.
211 Optionally, specify the `key` or `index` of the value to pop.
212 The `last` parameter is included to match the OrderedDict API. If `last`
213 is passed then the first or last item is returned based on its
214 truthiness.
215
216 At most one of `index`, `last` and `key` can be specified.
217
218 This is generally O(N) unless removing last item, then O(1).
219
220 Args:
221 key: The key of the value to pop
222 index: The index of the value to pop
223 last: Whether or not to pip the last item
224
225 Raises:
226 KeyError: If the dictionary is empty or a key is specified that is
227 not present
228 IndexError: If `index` is specified and is out of bounds
229 ValueError: If more than one of `last`, `index` and `key` are
230 specified
231
232 """
233 if not self:
234 raise KeyError('IndexedDict is empty')
235 if sum(x is not NOT_SET for x in (last, key, index)) > 1:
236 raise ValueError(
237 "Cannot specify more than one of key, index and last"
238 )
239 if key is not NOT_SET:
240 index, value = self._pop_key(key=key, has_default=False)
241 else:
242 if last is not NOT_SET:
243 index = -1 if last else 0
244 if index is NOT_SET:
245 index = -1
246 key, index, value = self._pop_index(index, has_default=False)
247 self._fix_indices_after_delete(starting_index=index)
248 return key, value
249
250 def move_to_end(self, key=NOT_SET, index=NOT_SET, last=True):
251 """Move an existing element to the end (or beginning if last==False).
252
253 Runs in O(N).
254 """
255 if index is NOT_SET and key is not NOT_SET:
256 index, value = self._dict[key]
257 elif index is not NOT_SET and key is NOT_SET:
258 key, value = self._list[index]
259
260 # Normalize index
261 if index < 0:
262 index += len(self._list)
263 else:
264 raise KEY_EQ_INDEX_ERROR
265
266 if last:
267 index_range = range(len(self._list) - 1, index - 1, -1)
268 self._dict[key] = (len(self._list) - 1, value)
269 else:
270 index_range = range(index + 1)
271 self._dict[key] = (0, value)
272
273 previous = (key, value)
274 for i in index_range:
275 self._dict[previous[0]] = i, previous[1]
276 previous, self._list[i] = self._list[i], previous
277
278 def copy(self):
279 """Return a shallow copy."""
280 ret = IndexedDict()
281 ret._dict = self._dict.copy()
282 ret._list = list(self._list)
283 return ret
284
285 def index(self, key):
286 """Return index of a record with given key.
287
288 Runs in O(1).
289 """
290 return self._dict[key][0]
291
292 def key(self, index):
293 """Return key of a record at given index.
294
295 Runs in O(1).
296 """
297 return self._list[index][0]
298
299 def __len__(self):
300 """Return number of elements stored."""
301 return len(self._list)
302
303 def __repr__(self):
304 return "{class_name}({data})".format(
305 class_name=self.__class__.__name__,
306 data=repr(self._list),
307 )
308
309 def __str__(self):
310 # When Python 3.5 support is dropped, we can rely on dict order and this
311 # can be simplified to:
312 # return "{class_name}({data})".format(
313 # class_name=self.__class__.__name__,
314 # data=repr(dict(self)),
315 # )
316 data = ', '.join(
317 '{k!r}: {v!r}'.format(k=k, v=v)
318 for k, v in self.items()
319 )
320 return "{class_name}({{{data}}})".format(
321 class_name=self.__class__.__name__,
322 data=data,
323 )
324
325 def __getitem__(self, key):
326 """Return value corresponding to given key.
327
328 Raises KeyError when the key is not present in the mapping.
329
330 Runs in O(1).
331 """
332 return self._dict[key][1]
333
334 def __setitem__(self, key, value):
335 """Set item with given key to given value.
336
337 If the key is already present in the mapping its order is unchanged,
338 if it is not then it's added to the last place.
339
340 Runs in O(1).
341 """
342 if key in self._dict:
343 index, old_value1 = self._dict[key]
344 self._list[index] = key, value
345 else:
346 index = len(self._list)
347 self._list.append((key, value))
348 self._dict[key] = index, value
349
350 def __delitem__(self, key):
351 """Remove item with given key from the mapping.
352
353 Runs in O(n), unless removing last item, then in O(1).
354 """
355 index, value = self._dict.pop(key)
356 key2, value2 = self._list.pop(index)
357 assert key == key2
358 assert value is value2
359
360 self._fix_indices_after_delete(index)
361
362 def __contains__(self, key):
363 """Check if a key is present in the mapping.
364
365 Runs in O(1).
366 """
367 return key in self._dict
368
369 def __iter__(self):
370 """Return iterator over the keys of the mapping in order."""
371 return (item[0] for item in self._list)
372
373 def _fix_indices_after_delete(self, starting_index=0):
374 for i, (k, v) in enumerate(self._list[starting_index:], starting_index):
375 self._dict[k] = (i, v)