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 ?
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.