blob: 75a807252827ebd50233758c5b8e517292cc0003 [file] [log] [blame]
Guido van Rossum64c06e32007-11-22 00:55:51 +00001# Copyright 2007 Google, Inc. All Rights Reserved.
2# Licensed to PSF under a Contributor Agreement.
3
4"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
5
6DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
7via collections; they are defined here only to alleviate certain
8bootstrapping issues. Unit tests are in test_collections.
9"""
10
11from abc import ABCMeta, abstractmethod
12
13__all__ = ["Hashable", "Iterable", "Iterator",
14 "Sized", "Container", "Callable",
15 "Set", "MutableSet",
16 "Mapping", "MutableMapping",
17 "MappingView", "KeysView", "ItemsView", "ValuesView",
18 "Sequence", "MutableSequence",
19 ]
20
21### ONE-TRICK PONIES ###
22
23class Hashable:
24 __metaclass__ = ABCMeta
25
26 @abstractmethod
27 def __hash__(self):
28 return 0
29
30 @classmethod
31 def __subclasshook__(cls, C):
32 if cls is Hashable:
33 for B in C.__mro__:
34 if "__hash__" in B.__dict__:
35 if B.__dict__["__hash__"]:
36 return True
37 break
38 return NotImplemented
39
40
41class Iterable:
42 __metaclass__ = ABCMeta
43
44 @abstractmethod
45 def __iter__(self):
46 while False:
47 yield None
48
49 @classmethod
50 def __subclasshook__(cls, C):
51 if cls is Iterable:
52 if any("__iter__" in B.__dict__ for B in C.__mro__):
53 return True
54 return NotImplemented
55
56Iterable.register(str)
57
58
59class Iterator:
60 __metaclass__ = ABCMeta
61
62 @abstractmethod
63 def __next__(self):
64 raise StopIteration
65
66 def __iter__(self):
67 return self
68
69 @classmethod
70 def __subclasshook__(cls, C):
71 if cls is Iterator:
72 if any("next" in B.__dict__ for B in C.__mro__):
73 return True
74 return NotImplemented
75
76
77class Sized:
78 __metaclass__ = ABCMeta
79
80 @abstractmethod
81 def __len__(self):
82 return 0
83
84 @classmethod
85 def __subclasshook__(cls, C):
86 if cls is Sized:
87 if any("__len__" in B.__dict__ for B in C.__mro__):
88 return True
89 return NotImplemented
90
91
92class Container:
93 __metaclass__ = ABCMeta
94
95 @abstractmethod
96 def __contains__(self, x):
97 return False
98
99 @classmethod
100 def __subclasshook__(cls, C):
101 if cls is Container:
102 if any("__contains__" in B.__dict__ for B in C.__mro__):
103 return True
104 return NotImplemented
105
106
107class Callable:
108 __metaclass__ = ABCMeta
109
110 @abstractmethod
111 def __contains__(self, x):
112 return False
113
114 @classmethod
115 def __subclasshook__(cls, C):
116 if cls is Callable:
117 if any("__call__" in B.__dict__ for B in C.__mro__):
118 return True
119 return NotImplemented
120
121
122### SETS ###
123
124
125class Set:
126 __metaclass__ = ABCMeta
127
128 """A set is a finite, iterable container.
129
130 This class provides concrete generic implementations of all
131 methods except for __contains__, __iter__ and __len__.
132
133 To override the comparisons (presumably for speed, as the
134 semantics are fixed), all you have to do is redefine __le__ and
135 then the other operations will automatically follow suit.
136 """
137
138 @abstractmethod
139 def __contains__(self, value):
140 return False
141
142 @abstractmethod
143 def __iter__(self):
144 while False:
145 yield None
146
147 @abstractmethod
148 def __len__(self):
149 return 0
150
151 def __le__(self, other):
152 if not isinstance(other, Set):
153 return NotImplemented
154 if len(self) > len(other):
155 return False
156 for elem in self:
157 if elem not in other:
158 return False
159 return True
160
161 def __lt__(self, other):
162 if not isinstance(other, Set):
163 return NotImplemented
164 return len(self) < len(other) and self.__le__(other)
165
166 def __eq__(self, other):
167 if not isinstance(other, Set):
168 return NotImplemented
169 return len(self) == len(other) and self.__le__(other)
170
171 @classmethod
172 def _from_iterable(cls, it):
173 return frozenset(it)
174
175 def __and__(self, other):
176 if not isinstance(other, Iterable):
177 return NotImplemented
178 return self._from_iterable(value for value in other if value in self)
179
Raymond Hettingerabf3fcf2008-01-30 00:01:07 +0000180 def isdisjoint(self, other):
181 for value in other:
182 if value in self:
183 return False
184 return True
185
Guido van Rossum64c06e32007-11-22 00:55:51 +0000186 def __or__(self, other):
187 if not isinstance(other, Iterable):
188 return NotImplemented
189 return self._from_iterable(itertools.chain(self, other))
190
191 def __sub__(self, other):
192 if not isinstance(other, Set):
193 if not isinstance(other, Iterable):
194 return NotImplemented
195 other = self._from_iterable(other)
196 return self._from_iterable(value for value in self
197 if value not in other)
198
199 def __xor__(self, other):
200 if not isinstance(other, Set):
201 if not isinstance(other, Iterable):
202 return NotImplemented
203 other = self._from_iterable(other)
204 return (self - other) | (other - self)
205
206 def _hash(self):
207 """Compute the hash value of a set.
208
209 Note that we don't define __hash__: not all sets are hashable.
210 But if you define a hashable set type, its __hash__ should
211 call this function.
212
213 This must be compatible __eq__.
214
215 All sets ought to compare equal if they contain the same
216 elements, regardless of how they are implemented, and
217 regardless of the order of the elements; so there's not much
218 freedom for __eq__ or __hash__. We match the algorithm used
219 by the built-in frozenset type.
220 """
221 MAX = sys.maxint
222 MASK = 2 * MAX + 1
223 n = len(self)
224 h = 1927868237 * (n + 1)
225 h &= MASK
226 for x in self:
227 hx = hash(x)
228 h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
229 h &= MASK
230 h = h * 69069 + 907133923
231 h &= MASK
232 if h > MAX:
233 h -= MASK + 1
234 if h == -1:
235 h = 590923713
236 return h
237
238Set.register(frozenset)
239
240
241class MutableSet(Set):
242
243 @abstractmethod
244 def add(self, value):
245 """Return True if it was added, False if already there."""
246 raise NotImplementedError
247
248 @abstractmethod
249 def discard(self, value):
250 """Return True if it was deleted, False if not there."""
251 raise NotImplementedError
252
Raymond Hettinger7d518f42008-01-30 00:08:31 +0000253 def remove(self, value):
254 """Remove an element. If not a member, raise a KeyError."""
255 if value not in self:
256 raise KeyError(value)
257 self.discard(value)
258
Guido van Rossum64c06e32007-11-22 00:55:51 +0000259 def pop(self):
260 """Return the popped value. Raise KeyError if empty."""
261 it = iter(self)
262 try:
263 value = it.__next__()
264 except StopIteration:
265 raise KeyError
266 self.discard(value)
267 return value
268
Guido van Rossum64c06e32007-11-22 00:55:51 +0000269 def clear(self):
270 """This is slow (creates N new iterators!) but effective."""
271 try:
272 while True:
273 self.pop()
274 except KeyError:
275 pass
276
277 def __ior__(self, it):
278 for value in it:
279 self.add(value)
280 return self
281
282 def __iand__(self, c):
283 for value in self:
284 if value not in c:
285 self.discard(value)
286 return self
287
288 def __ixor__(self, it):
Raymond Hettingere67420d2008-01-31 01:38:15 +0000289 if not isinstance(it, Set):
290 it = self._from_iterable(it)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000291 for value in it:
Raymond Hettingere67420d2008-01-31 01:38:15 +0000292 if value in self:
293 self.discard(value)
294 else:
295 self.add(value)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000296
297 def __isub__(self, it):
298 for value in it:
299 self.discard(value)
300 return self
301
302MutableSet.register(set)
303
304
305### MAPPINGS ###
306
307
308class Mapping:
309 __metaclass__ = ABCMeta
310
311 @abstractmethod
312 def __getitem__(self, key):
313 raise KeyError
314
315 def get(self, key, default=None):
316 try:
317 return self[key]
318 except KeyError:
319 return default
320
321 def __contains__(self, key):
322 try:
323 self[key]
324 except KeyError:
325 return False
326 else:
327 return True
328
329 @abstractmethod
330 def __len__(self):
331 return 0
332
333 @abstractmethod
334 def __iter__(self):
335 while False:
336 yield None
337
338 def keys(self):
339 return KeysView(self)
340
341 def items(self):
342 return ItemsView(self)
343
344 def values(self):
345 return ValuesView(self)
346
347
348class MappingView:
349 __metaclass__ = ABCMeta
350
351 def __init__(self, mapping):
352 self._mapping = mapping
353
354 def __len__(self):
355 return len(self._mapping)
356
357
358class KeysView(MappingView, Set):
359
360 def __contains__(self, key):
361 return key in self._mapping
362
363 def __iter__(self):
364 for key in self._mapping:
365 yield key
366
367KeysView.register(type({}.keys()))
368
369
370class ItemsView(MappingView, Set):
371
372 def __contains__(self, item):
373 key, value = item
374 try:
375 v = self._mapping[key]
376 except KeyError:
377 return False
378 else:
379 return v == value
380
381 def __iter__(self):
382 for key in self._mapping:
383 yield (key, self._mapping[key])
384
385ItemsView.register(type({}.items()))
386
387
388class ValuesView(MappingView):
389
390 def __contains__(self, value):
391 for key in self._mapping:
392 if value == self._mapping[key]:
393 return True
394 return False
395
396 def __iter__(self):
397 for key in self._mapping:
398 yield self._mapping[key]
399
400ValuesView.register(type({}.values()))
401
402
403class MutableMapping(Mapping):
404
405 @abstractmethod
406 def __setitem__(self, key, value):
407 raise KeyError
408
409 @abstractmethod
410 def __delitem__(self, key):
411 raise KeyError
412
413 __marker = object()
414
415 def pop(self, key, default=__marker):
416 try:
417 value = self[key]
418 except KeyError:
419 if default is self.__marker:
420 raise
421 return default
422 else:
423 del self[key]
424 return value
425
426 def popitem(self):
427 try:
428 key = next(iter(self))
429 except StopIteration:
430 raise KeyError
431 value = self[key]
432 del self[key]
433 return key, value
434
435 def clear(self):
436 try:
437 while True:
438 self.popitem()
439 except KeyError:
440 pass
441
442 def update(self, other=(), **kwds):
443 if isinstance(other, Mapping):
444 for key in other:
445 self[key] = other[key]
446 elif hasattr(other, "keys"):
447 for key in other.keys():
448 self[key] = other[key]
449 else:
450 for key, value in other:
451 self[key] = value
452 for key, value in kwds.items():
453 self[key] = value
454
455MutableMapping.register(dict)
456
457
458### SEQUENCES ###
459
460
461class Sequence:
462 __metaclass__ = ABCMeta
463
464 """All the operations on a read-only sequence.
465
466 Concrete subclasses must override __new__ or __init__,
467 __getitem__, and __len__.
468 """
469
470 @abstractmethod
471 def __getitem__(self, index):
472 raise IndexError
473
474 @abstractmethod
475 def __len__(self):
476 return 0
477
478 def __iter__(self):
479 i = 0
480 while True:
481 try:
482 v = self[i]
483 except IndexError:
484 break
485 yield v
486 i += 1
487
488 def __contains__(self, value):
489 for v in self:
490 if v == value:
491 return True
492 return False
493
494 def __reversed__(self):
495 for i in reversed(range(len(self))):
496 yield self[i]
497
498 def index(self, value):
499 for i, v in enumerate(self):
500 if v == value:
501 return i
502 raise ValueError
503
504 def count(self, value):
505 return sum(1 for v in self if v == value)
506
507Sequence.register(tuple)
508Sequence.register(basestring)
509Sequence.register(buffer)
510
511
512class MutableSequence(Sequence):
513
514 @abstractmethod
515 def __setitem__(self, index, value):
516 raise IndexError
517
518 @abstractmethod
519 def __delitem__(self, index):
520 raise IndexError
521
522 @abstractmethod
523 def insert(self, index, value):
524 raise IndexError
525
526 def append(self, value):
527 self.insert(len(self), value)
528
529 def reverse(self):
530 n = len(self)
531 for i in range(n//2):
532 self[i], self[n-i-1] = self[n-i-1], self[i]
533
534 def extend(self, values):
535 for v in values:
536 self.append(v)
537
538 def pop(self, index=-1):
539 v = self[index]
540 del self[index]
541 return v
542
543 def remove(self, value):
544 del self[self.index(value)]
545
546 def __iadd__(self, values):
547 self.extend(values)
548
549MutableSequence.register(list)