Is there a canonical way to check whether an iterable is ordered?

Chris Angelico rosuav at gmail.com
Fri Sep 19 13:25:04 CEST 2014


On Fri, Sep 19, 2014 at 8:59 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Here's a proof of concept of what would be allowed:
>
> import random
> class MyDict:
>     def __init__(self, items):
>         self._items = list(dict(items).items())
>         self._flags = [False, False, False]
>     def keys(self):
>         k = [item[0] for item in self._items]
>         self._check(0)
>         return k
>     def values(self):
>         k = [item[1] for item in self._items]
>         self._check(1)
>         return k
>     def items(self):
>         k = self._items[:]
>         self._check(2)
>         return k
>     def _check(self, i):
>         self._flags[i] = True
>         if self._flags == [True, True, True]:
>             random.shuffle(self._items)
>             self._flags = [False, False, False]

Also, this can't possibly offer the same guarantee. Watch:

d = MyDict(some_lot_of_items)
d.values(); d.items()
# mutate the dict in whatever way you like
pairs = zip(d.keys(), d.values())

This might well create mismatched pairs, because after generating the
keys() return value, the list gets shuffled, prior to generating
values() in the same expression. This would not be allowed.

ChrisA



More information about the Python-list mailing list