1 # Copyright 2007 Google, Inc. All Rights Reserved.
2 # Licensed to PSF under a Contributor Agreement.
4 """Abstract Base Classes (ABCs) for collections, according to PEP 3119.
6 DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
7 via collections; they are defined here only to alleviate certain
8 bootstrapping issues. Unit tests are in test_collections.
11 from abc import ABCMeta, abstractmethod
14 __all__ = ["Hashable", "Iterable", "Iterator",
15 "Sized", "Container", "Callable",
17 "Mapping", "MutableMapping",
18 "MappingView", "KeysView", "ItemsView", "ValuesView",
19 "Sequence", "MutableSequence",
22 ### ONE-TRICK PONIES ###
24 def _hasattr(C, attr):
26 return any(attr in B.__dict__ for B in C.__mro__)
27 except AttributeError:
29 return hasattr(C, attr)
33 __metaclass__ = ABCMeta
40 def __subclasshook__(cls, C):
44 if "__hash__" in B.__dict__:
45 if B.__dict__["__hash__"]:
48 except AttributeError:
50 if getattr(C, "__hash__", None):
56 __metaclass__ = ABCMeta
64 def __subclasshook__(cls, C):
66 if _hasattr(C, "__iter__"):
70 Iterable.register(str)
73 class Iterator(Iterable):
83 def __subclasshook__(cls, C):
85 if _hasattr(C, "next"):
91 __metaclass__ = ABCMeta
98 def __subclasshook__(cls, C):
100 if _hasattr(C, "__len__"):
102 return NotImplemented
106 __metaclass__ = ABCMeta
109 def __contains__(self, x):
113 def __subclasshook__(cls, C):
115 if _hasattr(C, "__contains__"):
117 return NotImplemented
121 __metaclass__ = ABCMeta
124 def __call__(self, *args, **kwds):
128 def __subclasshook__(cls, C):
130 if _hasattr(C, "__call__"):
132 return NotImplemented
138 class Set(Sized, Iterable, Container):
139 """A set is a finite, iterable container.
141 This class provides concrete generic implementations of all
142 methods except for __contains__, __iter__ and __len__.
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.
149 def __le__(self, other):
150 if not isinstance(other, Set):
151 return NotImplemented
152 if len(self) > len(other):
155 if elem not in other:
159 def __lt__(self, other):
160 if not isinstance(other, Set):
161 return NotImplemented
162 return len(self) < len(other) and self.__le__(other)
164 def __gt__(self, other):
165 if not isinstance(other, Set):
166 return NotImplemented
169 def __ge__(self, other):
170 if not isinstance(other, Set):
171 return NotImplemented
174 def __eq__(self, other):
175 if not isinstance(other, Set):
176 return NotImplemented
177 return len(self) == len(other) and self.__le__(other)
179 def __ne__(self, other):
180 return not (self == other)
183 def _from_iterable(cls, it):
184 '''Construct an instance of the class from any iterable input.
186 Must override this method if the class constructor signature
187 does not accept an iterable for an input.
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)
196 def isdisjoint(self, other):
202 def __or__(self, other):
203 if not isinstance(other, Iterable):
204 return NotImplemented
205 chain = (e for s in (self, other) for e in s)
206 return self._from_iterable(chain)
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)
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)
223 # Sets are not hashable by default, but subclasses can change this
227 """Compute the hash value of a set.
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
233 This must be compatible __eq__.
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.
244 h = 1927868237 * (n + 1)
248 h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
250 h = h * 69069 + 907133923
258 Set.register(frozenset)
261 class MutableSet(Set):
264 def add(self, value):
265 """Add an element."""
266 raise NotImplementedError
269 def discard(self, value):
270 """Remove an element. Do not raise an exception if absent."""
271 raise NotImplementedError
273 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)
280 """Return the popped value. Raise KeyError if empty."""
284 except StopIteration:
290 """This is slow (creates N new iterators!) but effective."""
297 def __ior__(self, it):
302 def __iand__(self, it):
303 for value in (self - it):
307 def __ixor__(self, it):
311 if not isinstance(it, Set):
312 it = self._from_iterable(it)
320 def __isub__(self, it):
328 MutableSet.register(set)
334 class Mapping(Sized, Iterable, Container):
337 def __getitem__(self, key):
340 def get(self, key, default=None):
346 def __contains__(self, key):
357 def itervalues(self):
363 yield (key, self[key])
369 return [(key, self[key]) for key in self]
372 return [self[key] for key in self]
374 # Mappings are not hashable by default, but subclasses can change this
377 def __eq__(self, other):
378 if not isinstance(other, Mapping):
379 return NotImplemented
380 return dict(self.items()) == dict(other.items())
382 def __ne__(self, other):
383 return not (self == other)
385 class MappingView(Sized):
387 def __init__(self, mapping):
388 self._mapping = mapping
391 return len(self._mapping)
394 return '{0.__class__.__name__}({0._mapping!r})'.format(self)
397 class KeysView(MappingView, Set):
400 def _from_iterable(self, it):
403 def __contains__(self, key):
404 return key in self._mapping
407 for key in self._mapping:
411 class ItemsView(MappingView, Set):
414 def _from_iterable(self, it):
417 def __contains__(self, item):
420 v = self._mapping[key]
427 for key in self._mapping:
428 yield (key, self._mapping[key])
431 class ValuesView(MappingView):
433 def __contains__(self, value):
434 for key in self._mapping:
435 if value == self._mapping[key]:
440 for key in self._mapping:
441 yield self._mapping[key]
444 class MutableMapping(Mapping):
447 def __setitem__(self, key, value):
451 def __delitem__(self, key):
456 def pop(self, key, default=__marker):
460 if default is self.__marker:
469 key = next(iter(self))
470 except StopIteration:
483 def update(*args, **kwds):
485 raise TypeError("update() takes at most 2 positional "
486 "arguments ({} given)".format(len(args)))
488 raise TypeError("update() takes at least 1 argument (0 given)")
490 other = args[1] if len(args) >= 2 else ()
492 if isinstance(other, Mapping):
494 self[key] = other[key]
495 elif hasattr(other, "keys"):
496 for key in other.keys():
497 self[key] = other[key]
499 for key, value in other:
501 for key, value in kwds.items():
504 def setdefault(self, key, default=None):
511 MutableMapping.register(dict)
517 class Sequence(Sized, Iterable, Container):
518 """All the operations on a read-only sequence.
520 Concrete subclasses must override __new__ or __init__,
521 __getitem__, and __len__.
525 def __getitem__(self, index):
538 def __contains__(self, value):
544 def __reversed__(self):
545 for i in reversed(range(len(self))):
548 def index(self, value):
549 for i, v in enumerate(self):
554 def count(self, value):
555 return sum(1 for v in self if v == value)
557 Sequence.register(tuple)
558 Sequence.register(basestring)
559 Sequence.register(buffer)
560 Sequence.register(xrange)
563 class MutableSequence(Sequence):
566 def __setitem__(self, index, value):
570 def __delitem__(self, index):
574 def insert(self, index, value):
577 def append(self, value):
578 self.insert(len(self), value)
582 for i in range(n//2):
583 self[i], self[n-i-1] = self[n-i-1], self[i]
585 def extend(self, values):
589 def pop(self, index=-1):
594 def remove(self, value):
595 del self[self.index(value)]
597 def __iadd__(self, values):
601 MutableSequence.register(list)