2

Earlier today i asked a question because I was not able to really understand the implementation of comparison operators using rich comparison methods. Thank you, to the accepted answer for well explaining the differences between the two.

Basically, from what I understood, Python 3 stopped the use of __cmp__() magic method. From now on,

The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering.

Thus, I thought that OrderedDict would be valid. But, to my surprise,

d1 = OrderedDict([(1,1)])
d2 = OrderedDict([(2,2)])
>>> dict1 < dict2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'collections.OrderedDict' and 'collections.OrderedDict'
>>> dict1.__lt__(dict2)
NotImplemented

So, why does OrderedDict is not implementing comparison operators ?

Note that in the comments of the answer of the linked question, we started to talk on the topic. One thing that was underlined, is why assume insertion order is how you want to compare things? You can always implement your own way to compare them explicitly.

Then why (even in Python 3),

list1 = [1,2,3]
list2 = [4,5,6]
>>> list1 < list2
True

Isn't a similar situation ?

scharette
  • 9,437
  • 8
  • 33
  • 67

2 Answers2

5

A "meaningful natural ordering" refers to a "natural" way to decide which of two objects is greater. It doesn't refer to whether the objects are ordered collections.

OrderedDict may impose an ordering on its entries, but there is no natural ordering relationship between two OrderedDicts.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • What about lexicographic on items? Could be argued to be rather natural, no? – Paul Panzer Dec 13 '17 at 21:56
  • @PaulPanzer: I might expand my answer, but the gist is that it's not relevant to OrderedDict use cases, it would have messed with compatibility with regular dicts on Python 2 (and intransitive `==` is bad enough), and after the early-Python "compare all the things" approach turned out to suck, I don't think they were eager to throw in comparison operators without a strong justification. – user2357112 Dec 13 '17 at 22:24
0

@scharette, I do agree that under certain angle OrderedDict really looks like a linked list with O(1) access time. Developers of cpython share this view in the comment to C implementation of the OrderedDict.

My answer to your question is simple. Nobody ever thought that far )

There were no comparison operators in the original proposal.

No proposals were added neither through bugs.python.org nor as a PEP

If you feel worth adding comparison operators to OrderedDict, please supmit an enhancment request at https://bugs.python.org/

Pak Uula
  • 2,750
  • 1
  • 8
  • 13