diff --git a/Lib/_collections_abc.py b/Lib/_collections_abc.py index b172f3f..47a54d4 100644 --- a/Lib/_collections_abc.py +++ b/Lib/_collections_abc.py @@ -14,7 +14,7 @@ __all__ = ["Awaitable", "Coroutine", "Hashable", "Iterable", "Iterator", "Generator", "Reversible", "Sized", "Container", "Callable", "Collection", "Set", "MutableSet", - "Mapping", "MutableMapping", + "Mapping", "MutableMapping", "OrderedMapping", "MappingView", "KeysView", "ItemsView", "ValuesView", "Sequence", "MutableSequence", "ByteString", @@ -764,6 +764,33 @@ class ValuesView(MappingView): ValuesView.register(dict_values) +class OrderedMapping(Mapping, Reversible): + + __slots__ = () + + """OrderedMapping provides a common base clase for ordered + Mapping types allowing them to interoperate. + + This class provides a concrete generic implementation of + __eq__ such that comparing to another OrderedMapping + is order-sensitive while comparing to an unordered Mapping + is order-insensitive. + + """ + + __missing = object() + + def __eq__(self, other): + if not isinstance(other, Mapping): + return NotImplemented + if len(self) != len(other): + return False + if isinstance(other, OrderedMapping): + return all(i == j for (i, j) in zip(self.items(), other.items())) + __missing = self.__missing + return all(self.get(k, __missing) == v for (k, v) in other.items()) + + class MutableMapping(Mapping): __slots__ = () diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py index bcc4291..5ba9e4b 100644 --- a/Lib/collections/__init__.py +++ b/Lib/collections/__init__.py @@ -68,7 +68,7 @@ class _OrderedDictValuesView(ValuesView): class _Link(object): __slots__ = 'prev', 'next', 'key', '__weakref__' -class OrderedDict(dict): +class OrderedDict(OrderedMapping, dict): 'Dictionary that remembers insertion order' # An inherited dict maps keys to values. # The inherited dict provides __getitem__, __len__, __contains__, and get. @@ -280,15 +280,6 @@ class OrderedDict(dict): self[key] = value return self - def __eq__(self, other): - '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive - while comparison to a regular mapping is order-insensitive. - - ''' - if isinstance(other, OrderedDict): - return dict.__eq__(self, other) and all(map(_eq, self, other)) - return dict.__eq__(self, other) - try: from _collections import OrderedDict