[Python-ideas] Adding collections.abc.Ordered
Serhiy Storchaka
storchaka at gmail.com
Sat Dec 26 07:00:50 EST 2015
On 07.11.15 00:11, Amir Rachum wrote:
> I am suggesting the addition of a collections abstract base class called
> "Ordered". Its meaning is that a collection's iteration order is part of
> its API. The bulk of this mail describes a use case for this. The reason
> I believe that such abstract base class is required is that there is no
> way to test this behavior in a given class. An ordered collection has
> the exact same interface as an unordered collection (e.g, dict and
> OrderedDict), other than a _promise_ of the API that the order in which
> this collection will be iterated has some sort of meaning (In
> OrderedDict, it is the order in which keys were added to it.)
>
> As examples, set, frozenset, dict and defaultdict should *not* be
> considered as ordered. list, OrderedDict, deque and tuple should be
> considered ordered.
Actually we already have such abstract class. It's typing.Reversible.
Iterating non-ordered collection doesn't make sense.
>>> issubclass(list, typing.Reversible)
True
>>> issubclass(collections.deque, typing.Reversible)
True
>>> issubclass(collections.OrderedDict, typing.Reversible)
True
>>> issubclass(type(collections.OrderedDict().items()),
typing.Reversible)
True
>>> issubclass(dict, typing.Reversible)
False
>>> issubclass(set, typing.Reversible)
False
>>> issubclass(frozenset, typing.Reversible)
False
>>> issubclass(collections.defaultdict, typing.Reversible)
False
>>> issubclass(type({}.items()), typing.Reversible)
False
Unfortunately the test returns False for tuple, str, bytes, bytearray,
and array:
>>> issubclass(tuple, typing.Reversible)
False
>>> issubclass(str, typing.Reversible)
False
>>> issubclass(bytes, typing.Reversible)
False
>>> issubclass(bytearray, typing.Reversible)
False
>>> issubclass(array.array, typing.Reversible)
False
This looks as a bug in typing.Reversible.
More information about the Python-ideas
mailing list