blob: ad5a9c0758da619b4b5b04166d63cfbfc35837c1 [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
Raymond Hettinger4c52f522008-06-23 03:29:28 +000012import sys
Guido van Rossum64c06e32007-11-22 00:55:51 +000013
14__all__ = ["Hashable", "Iterable", "Iterator",
15 "Sized", "Container", "Callable",
16 "Set", "MutableSet",
17 "Mapping", "MutableMapping",
18 "MappingView", "KeysView", "ItemsView", "ValuesView",
19 "Sequence", "MutableSequence",
20 ]
21
22### ONE-TRICK PONIES ###
23
Florent Xicluna47627d52010-03-08 15:20:28 +000024def _hasattr(C, attr):
25 try:
26 return any(attr in B.__dict__ for B in C.__mro__)
27 except AttributeError:
28 # Old-style class
29 return hasattr(C, attr)
30
31
Guido van Rossum64c06e32007-11-22 00:55:51 +000032class Hashable:
33 __metaclass__ = ABCMeta
34
35 @abstractmethod
36 def __hash__(self):
37 return 0
38
39 @classmethod
40 def __subclasshook__(cls, C):
41 if cls is Hashable:
Florent Xicluna47627d52010-03-08 15:20:28 +000042 try:
43 for B in C.__mro__:
44 if "__hash__" in B.__dict__:
45 if B.__dict__["__hash__"]:
46 return True
47 break
48 except AttributeError:
49 # Old-style class
50 if getattr(C, "__hash__", None):
51 return True
Guido van Rossum64c06e32007-11-22 00:55:51 +000052 return NotImplemented
53
54
55class Iterable:
56 __metaclass__ = ABCMeta
57
58 @abstractmethod
59 def __iter__(self):
60 while False:
61 yield None
62
63 @classmethod
64 def __subclasshook__(cls, C):
65 if cls is Iterable:
Florent Xicluna47627d52010-03-08 15:20:28 +000066 if _hasattr(C, "__iter__"):
Guido van Rossum64c06e32007-11-22 00:55:51 +000067 return True
68 return NotImplemented
69
70Iterable.register(str)
71
72
Raymond Hettingerc2bc0d12008-02-09 01:18:42 +000073class Iterator(Iterable):
Guido van Rossum64c06e32007-11-22 00:55:51 +000074
75 @abstractmethod
Raymond Hettingerf779e6f2009-01-28 23:02:26 +000076 def next(self):
Guido van Rossum64c06e32007-11-22 00:55:51 +000077 raise StopIteration
78
79 def __iter__(self):
80 return self
81
82 @classmethod
83 def __subclasshook__(cls, C):
84 if cls is Iterator:
Florent Xicluna47627d52010-03-08 15:20:28 +000085 if _hasattr(C, "next"):
Guido van Rossum64c06e32007-11-22 00:55:51 +000086 return True
87 return NotImplemented
88
89
90class Sized:
91 __metaclass__ = ABCMeta
92
93 @abstractmethod
94 def __len__(self):
95 return 0
96
97 @classmethod
98 def __subclasshook__(cls, C):
99 if cls is Sized:
Florent Xicluna47627d52010-03-08 15:20:28 +0000100 if _hasattr(C, "__len__"):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000101 return True
102 return NotImplemented
103
104
105class Container:
106 __metaclass__ = ABCMeta
107
108 @abstractmethod
109 def __contains__(self, x):
110 return False
111
112 @classmethod
113 def __subclasshook__(cls, C):
114 if cls is Container:
Florent Xicluna47627d52010-03-08 15:20:28 +0000115 if _hasattr(C, "__contains__"):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000116 return True
117 return NotImplemented
118
119
120class Callable:
121 __metaclass__ = ABCMeta
122
123 @abstractmethod
Raymond Hettinger10ac19b2008-03-03 22:19:58 +0000124 def __call__(self, *args, **kwds):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000125 return False
126
127 @classmethod
128 def __subclasshook__(cls, C):
129 if cls is Callable:
Florent Xicluna47627d52010-03-08 15:20:28 +0000130 if _hasattr(C, "__call__"):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000131 return True
132 return NotImplemented
133
134
135### SETS ###
136
137
Raymond Hettingerc2bc0d12008-02-09 01:18:42 +0000138class Set(Sized, Iterable, Container):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000139 """A set is a finite, iterable container.
140
141 This class provides concrete generic implementations of all
142 methods except for __contains__, __iter__ and __len__.
143
144 To override the comparisons (presumably for speed, as the
145 semantics are fixed), all you have to do is redefine __le__ and
146 then the other operations will automatically follow suit.
147 """
148
Guido van Rossum64c06e32007-11-22 00:55:51 +0000149 def __le__(self, other):
150 if not isinstance(other, Set):
151 return NotImplemented
152 if len(self) > len(other):
153 return False
154 for elem in self:
155 if elem not in other:
156 return False
157 return True
158
159 def __lt__(self, other):
160 if not isinstance(other, Set):
161 return NotImplemented
162 return len(self) < len(other) and self.__le__(other)
163
Raymond Hettingerd53f1c42008-02-08 23:34:21 +0000164 def __gt__(self, other):
165 if not isinstance(other, Set):
166 return NotImplemented
167 return other < self
168
169 def __ge__(self, other):
170 if not isinstance(other, Set):
171 return NotImplemented
172 return other <= self
173
Guido van Rossum64c06e32007-11-22 00:55:51 +0000174 def __eq__(self, other):
175 if not isinstance(other, Set):
176 return NotImplemented
177 return len(self) == len(other) and self.__le__(other)
178
Raymond Hettingerd53f1c42008-02-08 23:34:21 +0000179 def __ne__(self, other):
180 return not (self == other)
181
Guido van Rossum64c06e32007-11-22 00:55:51 +0000182 @classmethod
183 def _from_iterable(cls, it):
Raymond Hettinger017b6a32008-02-07 03:10:33 +0000184 '''Construct an instance of the class from any iterable input.
185
186 Must override this method if the class constructor signature
Raymond Hettinger2e827bf2008-02-09 03:34:52 +0000187 does not accept an iterable for an input.
Raymond Hettinger017b6a32008-02-07 03:10:33 +0000188 '''
Raymond Hettinger2e827bf2008-02-09 03:34:52 +0000189 return cls(it)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000190
191 def __and__(self, other):
192 if not isinstance(other, Iterable):
193 return NotImplemented
194 return self._from_iterable(value for value in other if value in self)
195
Raymond Hettingerabf3fcf2008-01-30 00:01:07 +0000196 def isdisjoint(self, other):
197 for value in other:
198 if value in self:
199 return False
200 return True
201
Guido van Rossum64c06e32007-11-22 00:55:51 +0000202 def __or__(self, other):
203 if not isinstance(other, Iterable):
204 return NotImplemented
Raymond Hettinger972fb072008-03-03 22:04:55 +0000205 chain = (e for s in (self, other) for e in s)
206 return self._from_iterable(chain)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000207
208 def __sub__(self, other):
209 if not isinstance(other, Set):
210 if not isinstance(other, Iterable):
211 return NotImplemented
212 other = self._from_iterable(other)
213 return self._from_iterable(value for value in self
214 if value not in other)
215
216 def __xor__(self, other):
217 if not isinstance(other, Set):
218 if not isinstance(other, Iterable):
219 return NotImplemented
220 other = self._from_iterable(other)
221 return (self - other) | (other - self)
222
Nick Coghlan48361f52008-08-11 15:45:58 +0000223 # Sets are not hashable by default, but subclasses can change this
224 __hash__ = None
225
Guido van Rossum64c06e32007-11-22 00:55:51 +0000226 def _hash(self):
227 """Compute the hash value of a set.
228
229 Note that we don't define __hash__: not all sets are hashable.
230 But if you define a hashable set type, its __hash__ should
231 call this function.
232
233 This must be compatible __eq__.
234
235 All sets ought to compare equal if they contain the same
236 elements, regardless of how they are implemented, and
237 regardless of the order of the elements; so there's not much
238 freedom for __eq__ or __hash__. We match the algorithm used
239 by the built-in frozenset type.
240 """
241 MAX = sys.maxint
242 MASK = 2 * MAX + 1
243 n = len(self)
244 h = 1927868237 * (n + 1)
245 h &= MASK
246 for x in self:
247 hx = hash(x)
248 h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
249 h &= MASK
250 h = h * 69069 + 907133923
251 h &= MASK
252 if h > MAX:
253 h -= MASK + 1
254 if h == -1:
255 h = 590923713
256 return h
257
258Set.register(frozenset)
259
260
261class MutableSet(Set):
262
263 @abstractmethod
264 def add(self, value):
Raymond Hettinger2d21d502009-01-13 09:08:32 +0000265 """Add an element."""
Guido van Rossum64c06e32007-11-22 00:55:51 +0000266 raise NotImplementedError
267
268 @abstractmethod
269 def discard(self, value):
Raymond Hettinger2d21d502009-01-13 09:08:32 +0000270 """Remove an element. Do not raise an exception if absent."""
Guido van Rossum64c06e32007-11-22 00:55:51 +0000271 raise NotImplementedError
272
Raymond Hettinger7d518f42008-01-30 00:08:31 +0000273 def remove(self, value):
274 """Remove an element. If not a member, raise a KeyError."""
275 if value not in self:
276 raise KeyError(value)
277 self.discard(value)
278
Guido van Rossum64c06e32007-11-22 00:55:51 +0000279 def pop(self):
280 """Return the popped value. Raise KeyError if empty."""
281 it = iter(self)
282 try:
Raymond Hettingerf779e6f2009-01-28 23:02:26 +0000283 value = next(it)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000284 except StopIteration:
285 raise KeyError
286 self.discard(value)
287 return value
288
Guido van Rossum64c06e32007-11-22 00:55:51 +0000289 def clear(self):
290 """This is slow (creates N new iterators!) but effective."""
291 try:
292 while True:
293 self.pop()
294 except KeyError:
295 pass
296
297 def __ior__(self, it):
298 for value in it:
299 self.add(value)
300 return self
301
Raymond Hettinger66c4a6b2009-04-01 18:50:56 +0000302 def __iand__(self, it):
303 for value in (self - it):
304 self.discard(value)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000305 return self
306
307 def __ixor__(self, it):
Raymond Hettingere67420d2008-01-31 01:38:15 +0000308 if not isinstance(it, Set):
309 it = self._from_iterable(it)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000310 for value in it:
Raymond Hettingere67420d2008-01-31 01:38:15 +0000311 if value in self:
312 self.discard(value)
313 else:
314 self.add(value)
Raymond Hettingere973c612008-01-31 01:42:11 +0000315 return self
Guido van Rossum64c06e32007-11-22 00:55:51 +0000316
317 def __isub__(self, it):
318 for value in it:
319 self.discard(value)
320 return self
321
322MutableSet.register(set)
323
324
325### MAPPINGS ###
326
327
Raymond Hettingerc2bc0d12008-02-09 01:18:42 +0000328class Mapping(Sized, Iterable, Container):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000329
330 @abstractmethod
331 def __getitem__(self, key):
332 raise KeyError
333
334 def get(self, key, default=None):
335 try:
336 return self[key]
337 except KeyError:
338 return default
339
340 def __contains__(self, key):
341 try:
342 self[key]
343 except KeyError:
344 return False
345 else:
346 return True
347
Georg Brandl60fbf7f2008-06-07 17:03:28 +0000348 def iterkeys(self):
349 return iter(self)
350
351 def itervalues(self):
352 for key in self:
353 yield self[key]
354
355 def iteritems(self):
356 for key in self:
357 yield (key, self[key])
358
Guido van Rossum64c06e32007-11-22 00:55:51 +0000359 def keys(self):
Georg Brandl60fbf7f2008-06-07 17:03:28 +0000360 return list(self)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000361
362 def items(self):
Georg Brandl60fbf7f2008-06-07 17:03:28 +0000363 return [(key, self[key]) for key in self]
Guido van Rossum64c06e32007-11-22 00:55:51 +0000364
365 def values(self):
Georg Brandl60fbf7f2008-06-07 17:03:28 +0000366 return [self[key] for key in self]
Guido van Rossum64c06e32007-11-22 00:55:51 +0000367
Nick Coghlan48361f52008-08-11 15:45:58 +0000368 # Mappings are not hashable by default, but subclasses can change this
369 __hash__ = None
370
Raymond Hettinger45eda642008-02-06 01:49:00 +0000371 def __eq__(self, other):
Benjamin Petersoneb318d32010-05-21 20:51:45 +0000372 if not isinstance(other, Mapping):
373 return NotImplemented
374 return dict(self.items()) == dict(other.items())
Raymond Hettinger45eda642008-02-06 01:49:00 +0000375
376 def __ne__(self, other):
377 return not (self == other)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000378
Raymond Hettingerc2bc0d12008-02-09 01:18:42 +0000379class MappingView(Sized):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000380
381 def __init__(self, mapping):
382 self._mapping = mapping
383
384 def __len__(self):
385 return len(self._mapping)
386
Raymond Hettingerb31a6d02009-02-27 08:09:47 +0000387 def __repr__(self):
388 return '{0.__class__.__name__}({0._mapping!r})'.format(self)
389
Guido van Rossum64c06e32007-11-22 00:55:51 +0000390
391class KeysView(MappingView, Set):
392
393 def __contains__(self, key):
394 return key in self._mapping
395
396 def __iter__(self):
397 for key in self._mapping:
398 yield key
399
Guido van Rossum64c06e32007-11-22 00:55:51 +0000400
401class ItemsView(MappingView, Set):
402
403 def __contains__(self, item):
404 key, value = item
405 try:
406 v = self._mapping[key]
407 except KeyError:
408 return False
409 else:
410 return v == value
411
412 def __iter__(self):
413 for key in self._mapping:
414 yield (key, self._mapping[key])
415
Guido van Rossum64c06e32007-11-22 00:55:51 +0000416
417class ValuesView(MappingView):
418
419 def __contains__(self, value):
420 for key in self._mapping:
421 if value == self._mapping[key]:
422 return True
423 return False
424
425 def __iter__(self):
426 for key in self._mapping:
427 yield self._mapping[key]
428
Guido van Rossum64c06e32007-11-22 00:55:51 +0000429
430class MutableMapping(Mapping):
431
432 @abstractmethod
433 def __setitem__(self, key, value):
434 raise KeyError
435
436 @abstractmethod
437 def __delitem__(self, key):
438 raise KeyError
439
440 __marker = object()
441
442 def pop(self, key, default=__marker):
443 try:
444 value = self[key]
445 except KeyError:
446 if default is self.__marker:
447 raise
448 return default
449 else:
450 del self[key]
451 return value
452
453 def popitem(self):
454 try:
455 key = next(iter(self))
456 except StopIteration:
457 raise KeyError
458 value = self[key]
459 del self[key]
460 return key, value
461
462 def clear(self):
463 try:
464 while True:
465 self.popitem()
466 except KeyError:
467 pass
468
469 def update(self, other=(), **kwds):
470 if isinstance(other, Mapping):
471 for key in other:
472 self[key] = other[key]
473 elif hasattr(other, "keys"):
474 for key in other.keys():
475 self[key] = other[key]
476 else:
477 for key, value in other:
478 self[key] = value
479 for key, value in kwds.items():
480 self[key] = value
481
Raymond Hettinger45eda642008-02-06 01:49:00 +0000482 def setdefault(self, key, default=None):
483 try:
484 return self[key]
485 except KeyError:
486 self[key] = default
487 return default
488
Guido van Rossum64c06e32007-11-22 00:55:51 +0000489MutableMapping.register(dict)
490
491
492### SEQUENCES ###
493
494
Raymond Hettingerc2bc0d12008-02-09 01:18:42 +0000495class Sequence(Sized, Iterable, Container):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000496 """All the operations on a read-only sequence.
497
498 Concrete subclasses must override __new__ or __init__,
499 __getitem__, and __len__.
500 """
501
502 @abstractmethod
503 def __getitem__(self, index):
504 raise IndexError
505
Guido van Rossum64c06e32007-11-22 00:55:51 +0000506 def __iter__(self):
507 i = 0
Raymond Hettinger18a1ffc2008-02-08 23:02:27 +0000508 try:
509 while True:
Guido van Rossum64c06e32007-11-22 00:55:51 +0000510 v = self[i]
Raymond Hettinger18a1ffc2008-02-08 23:02:27 +0000511 yield v
512 i += 1
513 except IndexError:
514 return
Guido van Rossum64c06e32007-11-22 00:55:51 +0000515
516 def __contains__(self, value):
517 for v in self:
518 if v == value:
519 return True
520 return False
521
522 def __reversed__(self):
523 for i in reversed(range(len(self))):
524 yield self[i]
525
526 def index(self, value):
527 for i, v in enumerate(self):
528 if v == value:
529 return i
530 raise ValueError
531
532 def count(self, value):
533 return sum(1 for v in self if v == value)
534
535Sequence.register(tuple)
536Sequence.register(basestring)
537Sequence.register(buffer)
Raymond Hettinger8c56f882009-02-24 12:23:23 +0000538Sequence.register(xrange)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000539
540
541class MutableSequence(Sequence):
542
543 @abstractmethod
544 def __setitem__(self, index, value):
545 raise IndexError
546
547 @abstractmethod
548 def __delitem__(self, index):
549 raise IndexError
550
551 @abstractmethod
552 def insert(self, index, value):
553 raise IndexError
554
555 def append(self, value):
556 self.insert(len(self), value)
557
558 def reverse(self):
559 n = len(self)
560 for i in range(n//2):
561 self[i], self[n-i-1] = self[n-i-1], self[i]
562
563 def extend(self, values):
564 for v in values:
565 self.append(v)
566
567 def pop(self, index=-1):
568 v = self[index]
569 del self[index]
570 return v
571
572 def remove(self, value):
573 del self[self.index(value)]
574
575 def __iadd__(self, values):
576 self.extend(values)
Raymond Hettingerfceb5d42009-05-18 15:51:59 +0000577 return self
Guido van Rossum64c06e32007-11-22 00:55:51 +0000578
579MutableSequence.register(list)