blob: 6c27e66be5f45c9e6f5d0eaf42b84b33a8bbb0ad [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):
Raymond Hettinger017b6a32008-02-07 03:10:33 +0000173 '''Construct an instance of the class from any iterable input.
174
175 Must override this method if the class constructor signature
176 will not accept a frozenset for an input.
177 '''
178 return cls(frozenset(it))
Guido van Rossum64c06e32007-11-22 00:55:51 +0000179
180 def __and__(self, other):
181 if not isinstance(other, Iterable):
182 return NotImplemented
183 return self._from_iterable(value for value in other if value in self)
184
Raymond Hettingerabf3fcf2008-01-30 00:01:07 +0000185 def isdisjoint(self, other):
186 for value in other:
187 if value in self:
188 return False
189 return True
190
Guido van Rossum64c06e32007-11-22 00:55:51 +0000191 def __or__(self, other):
192 if not isinstance(other, Iterable):
193 return NotImplemented
194 return self._from_iterable(itertools.chain(self, other))
195
196 def __sub__(self, other):
197 if not isinstance(other, Set):
198 if not isinstance(other, Iterable):
199 return NotImplemented
200 other = self._from_iterable(other)
201 return self._from_iterable(value for value in self
202 if value not in other)
203
204 def __xor__(self, other):
205 if not isinstance(other, Set):
206 if not isinstance(other, Iterable):
207 return NotImplemented
208 other = self._from_iterable(other)
209 return (self - other) | (other - self)
210
211 def _hash(self):
212 """Compute the hash value of a set.
213
214 Note that we don't define __hash__: not all sets are hashable.
215 But if you define a hashable set type, its __hash__ should
216 call this function.
217
218 This must be compatible __eq__.
219
220 All sets ought to compare equal if they contain the same
221 elements, regardless of how they are implemented, and
222 regardless of the order of the elements; so there's not much
223 freedom for __eq__ or __hash__. We match the algorithm used
224 by the built-in frozenset type.
225 """
226 MAX = sys.maxint
227 MASK = 2 * MAX + 1
228 n = len(self)
229 h = 1927868237 * (n + 1)
230 h &= MASK
231 for x in self:
232 hx = hash(x)
233 h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
234 h &= MASK
235 h = h * 69069 + 907133923
236 h &= MASK
237 if h > MAX:
238 h -= MASK + 1
239 if h == -1:
240 h = 590923713
241 return h
242
243Set.register(frozenset)
244
245
246class MutableSet(Set):
247
248 @abstractmethod
249 def add(self, value):
250 """Return True if it was added, False if already there."""
251 raise NotImplementedError
252
253 @abstractmethod
254 def discard(self, value):
255 """Return True if it was deleted, False if not there."""
256 raise NotImplementedError
257
Raymond Hettinger7d518f42008-01-30 00:08:31 +0000258 def remove(self, value):
259 """Remove an element. If not a member, raise a KeyError."""
260 if value not in self:
261 raise KeyError(value)
262 self.discard(value)
263
Guido van Rossum64c06e32007-11-22 00:55:51 +0000264 def pop(self):
265 """Return the popped value. Raise KeyError if empty."""
266 it = iter(self)
267 try:
268 value = it.__next__()
269 except StopIteration:
270 raise KeyError
271 self.discard(value)
272 return value
273
Guido van Rossum64c06e32007-11-22 00:55:51 +0000274 def clear(self):
275 """This is slow (creates N new iterators!) but effective."""
276 try:
277 while True:
278 self.pop()
279 except KeyError:
280 pass
281
282 def __ior__(self, it):
283 for value in it:
284 self.add(value)
285 return self
286
287 def __iand__(self, c):
288 for value in self:
289 if value not in c:
290 self.discard(value)
291 return self
292
293 def __ixor__(self, it):
Raymond Hettingere67420d2008-01-31 01:38:15 +0000294 if not isinstance(it, Set):
295 it = self._from_iterable(it)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000296 for value in it:
Raymond Hettingere67420d2008-01-31 01:38:15 +0000297 if value in self:
298 self.discard(value)
299 else:
300 self.add(value)
Raymond Hettingere973c612008-01-31 01:42:11 +0000301 return self
Guido van Rossum64c06e32007-11-22 00:55:51 +0000302
303 def __isub__(self, it):
304 for value in it:
305 self.discard(value)
306 return self
307
308MutableSet.register(set)
309
310
311### MAPPINGS ###
312
313
314class Mapping:
315 __metaclass__ = ABCMeta
316
317 @abstractmethod
318 def __getitem__(self, key):
319 raise KeyError
320
321 def get(self, key, default=None):
322 try:
323 return self[key]
324 except KeyError:
325 return default
326
327 def __contains__(self, key):
328 try:
329 self[key]
330 except KeyError:
331 return False
332 else:
333 return True
334
335 @abstractmethod
336 def __len__(self):
337 return 0
338
339 @abstractmethod
340 def __iter__(self):
341 while False:
342 yield None
343
344 def keys(self):
345 return KeysView(self)
346
347 def items(self):
348 return ItemsView(self)
349
350 def values(self):
351 return ValuesView(self)
352
Raymond Hettinger45eda642008-02-06 01:49:00 +0000353 def __eq__(self, other):
354 return isinstance(other, Mapping) and \
355 dict(self.items()) == dict(other.items())
356
357 def __ne__(self, other):
358 return not (self == other)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000359
360class MappingView:
361 __metaclass__ = ABCMeta
362
363 def __init__(self, mapping):
364 self._mapping = mapping
365
366 def __len__(self):
367 return len(self._mapping)
368
369
370class KeysView(MappingView, Set):
371
372 def __contains__(self, key):
373 return key in self._mapping
374
375 def __iter__(self):
376 for key in self._mapping:
377 yield key
378
379KeysView.register(type({}.keys()))
380
381
382class ItemsView(MappingView, Set):
383
384 def __contains__(self, item):
385 key, value = item
386 try:
387 v = self._mapping[key]
388 except KeyError:
389 return False
390 else:
391 return v == value
392
393 def __iter__(self):
394 for key in self._mapping:
395 yield (key, self._mapping[key])
396
397ItemsView.register(type({}.items()))
398
399
400class ValuesView(MappingView):
401
402 def __contains__(self, value):
403 for key in self._mapping:
404 if value == self._mapping[key]:
405 return True
406 return False
407
408 def __iter__(self):
409 for key in self._mapping:
410 yield self._mapping[key]
411
412ValuesView.register(type({}.values()))
413
414
415class MutableMapping(Mapping):
416
417 @abstractmethod
418 def __setitem__(self, key, value):
419 raise KeyError
420
421 @abstractmethod
422 def __delitem__(self, key):
423 raise KeyError
424
425 __marker = object()
426
427 def pop(self, key, default=__marker):
428 try:
429 value = self[key]
430 except KeyError:
431 if default is self.__marker:
432 raise
433 return default
434 else:
435 del self[key]
436 return value
437
438 def popitem(self):
439 try:
440 key = next(iter(self))
441 except StopIteration:
442 raise KeyError
443 value = self[key]
444 del self[key]
445 return key, value
446
447 def clear(self):
448 try:
449 while True:
450 self.popitem()
451 except KeyError:
452 pass
453
454 def update(self, other=(), **kwds):
455 if isinstance(other, Mapping):
456 for key in other:
457 self[key] = other[key]
458 elif hasattr(other, "keys"):
459 for key in other.keys():
460 self[key] = other[key]
461 else:
462 for key, value in other:
463 self[key] = value
464 for key, value in kwds.items():
465 self[key] = value
466
Raymond Hettinger45eda642008-02-06 01:49:00 +0000467 def setdefault(self, key, default=None):
468 try:
469 return self[key]
470 except KeyError:
471 self[key] = default
472 return default
473
Guido van Rossum64c06e32007-11-22 00:55:51 +0000474MutableMapping.register(dict)
475
476
477### SEQUENCES ###
478
479
480class Sequence:
481 __metaclass__ = ABCMeta
482
483 """All the operations on a read-only sequence.
484
485 Concrete subclasses must override __new__ or __init__,
486 __getitem__, and __len__.
487 """
488
489 @abstractmethod
490 def __getitem__(self, index):
491 raise IndexError
492
493 @abstractmethod
494 def __len__(self):
495 return 0
496
497 def __iter__(self):
498 i = 0
499 while True:
500 try:
501 v = self[i]
502 except IndexError:
503 break
504 yield v
505 i += 1
506
507 def __contains__(self, value):
508 for v in self:
509 if v == value:
510 return True
511 return False
512
513 def __reversed__(self):
514 for i in reversed(range(len(self))):
515 yield self[i]
516
517 def index(self, value):
518 for i, v in enumerate(self):
519 if v == value:
520 return i
521 raise ValueError
522
523 def count(self, value):
524 return sum(1 for v in self if v == value)
525
526Sequence.register(tuple)
527Sequence.register(basestring)
528Sequence.register(buffer)
529
530
531class MutableSequence(Sequence):
532
533 @abstractmethod
534 def __setitem__(self, index, value):
535 raise IndexError
536
537 @abstractmethod
538 def __delitem__(self, index):
539 raise IndexError
540
541 @abstractmethod
542 def insert(self, index, value):
543 raise IndexError
544
545 def append(self, value):
546 self.insert(len(self), value)
547
548 def reverse(self):
549 n = len(self)
550 for i in range(n//2):
551 self[i], self[n-i-1] = self[n-i-1], self[i]
552
553 def extend(self, values):
554 for v in values:
555 self.append(v)
556
557 def pop(self, index=-1):
558 v = self[index]
559 del self[index]
560 return v
561
562 def remove(self, value):
563 del self[self.index(value)]
564
565 def __iadd__(self, values):
566 self.extend(values)
567
568MutableSequence.register(list)