__hash__ and ordered vs. unordered collections

Chris Angelico rosuav at gmail.com
Mon Nov 20 15:17:32 EST 2017


On Tue, Nov 21, 2017 at 6:50 AM, Josh B. <jabronson at gmail.com> wrote:
> On Monday, November 20, 2017 at 1:55:26 PM UTC-5, Chris Angelico wrote:
>> But what you have is the strangeness of non-transitive equality, which
>> is likely to cause problems.
>
> But this is exactly how Python's built-in dict and OrderedDict behave:
>
>>>> od = OrderedDict([(1, 0), (2, 0), (3, 0)])
>>>> od2 = OrderedDict([(3, 0), (2, 0), (1, 0)])
>>>> ud = dict(od)
>>>> od == ud
> True
>>>> od2 == ud
> True
>>>> od == od2
> False
>
>
> Given that, it would seem wrong for our MyOrderedColl.__eq__ to not behave similarly.
>
> Or are you suggesting that OrderedDict.__eq__ should not have been implemented this way in the first place?
>
>
>> So the question is: are you willing to
>> accept the bizarre behaviour of non-transitive equality?
>
> Forget what I'm personally willing to do :)
> The question here actually is to tease out what Python's existing design is telling us to do.
>
> If it helps, substitute "frozenset" for "MyColl" and "FrozenOrderedSet" for "MyOrderedColl". How would you implement their __eq__ methods? What would be the correct design for our hypothetical frozen(ordered)set library? What would be more useful, intuitive, and usable for our users?
>
> Thanks very much for the good examples and for helping me clarify the question!
>

What I'm saying is that non-transitive equality can cause a lot of
confusion in sets/dicts; since OrderedDict and dict are unhashable,
they won't themselves be problematic, and Python doesn't have a
built-in FrozenOrderedSet. So there isn't really a precedent here, and
it's up to you to decide how you want to deal with this.

Basically, you're going to have to accept one of two situations:
* Either your class doesn't behave the same way dict and OD do
* Or your class, when put into a set, depends on ordering.

Neither is perfect. You have to take your pick between them.

ChrisA



More information about the Python-list mailing list