__hash__ and ordered vs. unordered collections

Josh B. jabronson at gmail.com
Tue Nov 21 12:43:54 EST 2017


On Monday, November 20, 2017 at 3:17:49 PM UTC-5, Chris Angelico wrote:
> Neither is perfect. You have to take your pick between them.

Right on, thanks for weighing in, Chris. Your responses have been very helpful.

I wouldn't feel comfortable claiming the authority to make this call alone. But fortunately I reached out to Raymond Hettinger and am delighted to have his guidance, pasted below. Great to have this predicament resolved.

In case of interest, I've implemented Raymond's advice in the latest release of bidict, the bidirectional map library I authored <http://bidict.rtfd.io>. Feedback always welcome.

Thanks,
Josh

---------- Forwarded message ----------
From: Raymond Hettinger <r... at ....com>
Date: Mon, Nov 20, 2017 at 4:46 PM
Subject: Re: __hash__ and ordered vs. unordered collections
To: jab at math.brown.edu


If you want to make ordered and unordered collections interoperable, I would just let equality be unordered all the time.  You can always provide a separate method for an ordered_comparison.

IMO, the design for __eq__ in collections.OrderedDict was a mistake.  It violates the Liskov Substitution Principle which would let ordered dicts always be substituted whereever regular dicts were expected.  It is simpler to have comparisons be unordered everywhere.

But there are no perfect solutions.  A user of an ordered collection may rightfully expect an ordered comparison, while a user of both collections may rightfully expect them to be mutually substitutable.


Raymond



More information about the Python-list mailing list