On 07.07.20 19:09, Christopher Barker wrote:

On Tue, Jul 7, 2020 at 6:56 AM Dominik Vilsmeier <dominik.vilsmeier@gmx.de> wrote:
Well, the point is that this "except comparisons" is not quite true:

     >>> i = {'a': []}.items()
     >>> s = {('a', 1)}
     >>> i == s
     TypeError: unhashable type: 'list'

If passed a set as `other` operand, dict_items seems to decide to
convert itself to a set, for no obvious reasons since, as you mentioned,
it does know how to compare itself to another view containing
non-hashable values:

     >>> i == {'a': {}}.items()
     False

So if you're dealing with items views and want to compare them to a set
representing dict items, then you need an extra `try/except` in order to
handle non-hashable values in the items view. Not only does this require
an extra precautionary step, it also seems strange given that in Python
you can compare all sorts of objects without exceptions being raised. I
can't think of any another built-in type that would raise an exception
on equality `==` comparison. dict_items seems to make an exception to
that rule.

I think this really is a bug (well, missing feature). It surely, *could* be implemented to work, but maybe not efficiently or easily, so may well not be worth it -- is the use case of comparing a dict_items with another dict_items really helpful?

I think it can be done both efficient and easy, since the current implementation has chosen that converting the view to a set fulfills these requirements. So all you'd have to do is to catch this TypeError inside __eq__ and return False since a `set` can never contain non-hashable elements. Note that it's the comparison with a `set` that causes this TypeError, not the one between two dict views.


In fact, my first thought was that the way to do the comparison is to convert to a dict, rather than a set, and then do the compare. And then I realized that dict_items don't exist without a dict anyway, so you really should be comparing the "host" dicts anyway. Which leaves exactly no use cases for this operation.

I tested converting the `set` to an items view via `dict(a_set).items()` and then use this for the __eq__ comparison but it is quite a bit slower than comparing a view to the set directly (if it doesn't contain any non-hashable values); after all it creates a new object including memory allocation.