# Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
via collections; they are defined here only to alleviate certain
bootstrapping issues. Unit tests are in test_collections.
from abc import ABCMeta, abstractmethod
__all__ = ["Hashable", "Iterable", "Iterator",
"Sized", "Container", "Callable",
"Mapping", "MutableMapping",
"MappingView", "KeysView", "ItemsView", "ValuesView",
"Sequence", "MutableSequence",
return any(attr in B.__dict__ for B in C.__mro__)
def __subclasshook__(cls, C):
if "__hash__" in B.__dict__:
if B.__dict__["__hash__"]:
if getattr(C, "__hash__", None):
def __subclasshook__(cls, C):
if _hasattr(C, "__iter__"):
class Iterator(Iterable):
'Return the next item from the iterator. When exhausted, raise StopIteration'
def __subclasshook__(cls, C):
if _hasattr(C, "next") and _hasattr(C, "__iter__"):
def __subclasshook__(cls, C):
if _hasattr(C, "__len__"):
def __contains__(self, x):
def __subclasshook__(cls, C):
if _hasattr(C, "__contains__"):
def __call__(self, *args, **kwds):
def __subclasshook__(cls, C):
if _hasattr(C, "__call__"):
class Set(Sized, Iterable, Container):
"""A set is a finite, iterable container.
This class provides concrete generic implementations of all
methods except for __contains__, __iter__ and __len__.
To override the comparisons (presumably for speed, as the
semantics are fixed), redefine __le__ and __ge__,
then the other operations will automatically follow suit.
if not isinstance(other, Set):
if len(self) > len(other):
if not isinstance(other, Set):
return len(self) < len(other) and self.__le__(other)
if not isinstance(other, Set):
return len(self) > len(other) and self.__ge__(other)
if not isinstance(other, Set):
if len(self) < len(other):
if not isinstance(other, Set):
return len(self) == len(other) and self.__le__(other)
return not (self == other)
def _from_iterable(cls, it):
'''Construct an instance of the class from any iterable input.
Must override this method if the class constructor signature
does not accept an iterable for an input.
def __and__(self, other):
if not isinstance(other, Iterable):
return self._from_iterable(value for value in other if value in self)
def isdisjoint(self, other):
'Return True if two sets have a null intersection.'
if not isinstance(other, Iterable):
chain = (e for s in (self, other) for e in s)
return self._from_iterable(chain)
def __sub__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
other = self._from_iterable(other)
return self._from_iterable(value for value in self
def __rsub__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
other = self._from_iterable(other)
return self._from_iterable(value for value in other
def __xor__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
other = self._from_iterable(other)
return (self - other) | (other - self)
# Sets are not hashable by default, but subclasses can change this
"""Compute the hash value of a set.
Note that we don't define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
This must be compatible __eq__.
All sets ought to compare equal if they contain the same
elements, regardless of how they are implemented, and
regardless of the order of the elements; so there's not much
freedom for __eq__ or __hash__. We match the algorithm used
by the built-in frozenset type.
h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
h = h * 69069 + 907133923
"""A mutable set is a finite, iterable container.
This class provides concrete generic implementations of all
methods except for __contains__, __iter__, __len__,
To override the comparisons (presumably for speed, as the
semantics are fixed), all you have to do is redefine __le__ and
then the other operations will automatically follow suit.
raise NotImplementedError
def discard(self, value):
"""Remove an element. Do not raise an exception if absent."""
raise NotImplementedError
"""Remove an element. If not a member, raise a KeyError."""
"""Return the popped value. Raise KeyError if empty."""
"""This is slow (creates N new iterators!) but effective."""
for value in (self - it):
if not isinstance(it, Set):
it = self._from_iterable(it)
class Mapping(Sized, Iterable, Container):
"""A Mapping is a generic container for associating key/value
This class provides concrete generic implementations of all
methods except for __getitem__, __iter__, and __len__.
def __getitem__(self, key):
def get(self, key, default=None):
'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
def __contains__(self, key):
'D.iterkeys() -> an iterator over the keys of D'
'D.itervalues() -> an iterator over the values of D'
'D.iteritems() -> an iterator over the (key, value) items of D'
"D.keys() -> list of D's keys"
"D.items() -> list of D's (key, value) pairs, as 2-tuples"
return [(key, self[key]) for key in self]
"D.values() -> list of D's values"
return [self[key] for key in self]
# Mappings are not hashable by default, but subclasses can change this
if not isinstance(other, Mapping):
return dict(self.items()) == dict(other.items())
return not (self == other)
class MappingView(Sized):
def __init__(self, mapping):
return len(self._mapping)
return '{0.__class__.__name__}({0._mapping!r})'.format(self)
class KeysView(MappingView, Set):
def _from_iterable(self, it):
def __contains__(self, key):
return key in self._mapping
for key in self._mapping:
KeysView.register(type({}.viewkeys()))
class ItemsView(MappingView, Set):
def _from_iterable(self, it):
def __contains__(self, item):
for key in self._mapping:
yield (key, self._mapping[key])
ItemsView.register(type({}.viewitems()))
class ValuesView(MappingView):
def __contains__(self, value):
for key in self._mapping:
if value == self._mapping[key]:
for key in self._mapping:
ValuesView.register(type({}.viewvalues()))
class MutableMapping(Mapping):
"""A MutableMapping is a generic container for associating
This class provides concrete generic implementations of all
methods except for __getitem__, __setitem__, __delitem__,