[Python-ideas] Fwd: Why do equality tests between OrderedDict keys/values views behave not as expected?

Eric Snow ericsnowcurrently at gmail.com
Thu Dec 17 14:05:53 EST 2015


On Thu, Dec 17, 2015 at 8:57 AM, Andrew Barnert via Python-ideas
<python-ideas at python.org> wrote:
> I think the first issue is that, if the comparison behavior of dict views isn't documented anywhere, it probably should be. (Even if the intended rule is just "comparisons may not be meaningful or do different things in different implementations, don't use them for anything", that could be documented.)

The views are documented as "set-like" and tied to the Set ABC. [1]
So comparision operations should match the same semantics as for sets.

  [snip]
> Finally, why should these comparisons be sequence-like? Yes, OrderedDict and its views do have a defined order, but they still don't act like sequences in other ways. You can't subscript or slice them, they follow dict rather than sequence rules for modifying during iteration (although I believe those rules aren't enforced in the code so you get arbitrary exceptions or wrong values instead of the RuntimeError from dict?), they fail isinstance(x, Sequence), etc. What other non-sequence types implement sequence comparisons?

Yep.  If you want to work with a sequence then you have to convert the
OrderedDict to a list or other sequence.  The same goes for the views,
which *do* preserve order during iteration (e.g. "list(od.keys())").

>
> Maybe what you really want is new methods to get sequence-like (but with O(1) __contains__ and friends) rather than set-like views, including implementing the Sequence ABC, which only exist on OrderedDict, compare like sequences, don't provide set operations or implement Set, etc. Then you can be explicit about which one you want. The question is, are you going to actually want the sequence-like views often enough for it to be worth adding all of that code?

I've spoken with folks that have use cases for
OrderedDict-as-a-sequence, but they were always able to use something
else that met their needs more directly anyway.

-eric

[1] https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects


More information about the Python-ideas mailing list