What does python 2.7 use to sort vanilla class instances? I'm interested in the default sorting behavior.
Suppose I have the class
class S():
pass
Then I can create a couple of instances, and sort them:
a = S(); b = S(); c = S()
l = [(a,'a'), (b,'b') ,(c, 'c')]
sorted(l)
This will print some sorting of the objects. Now I have a two part question:
__hash__(), and thus their id()? __hash__() to influence the sorting behavior?Python 3's built-in sorting makes use of the __lt__ method in your class.
The rich comparison methods are special in Python, since they can return a special NotImplemented type if there is not __lt__ defined - take a look at the docs on this page: http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy
Since the truth value of NotImplemented is True, any boolean comparison that gets NotImplemented will continue as if the first element actually is less than the second, which will cause the sort to leave the list in the same order as it was.
Take a look at the interactive shell. You can see how the truth values would be used in a sort, and that Python thinks that both objects are less than each other:
>>> class S():
... pass
...
>>> a = S()
>>> b = S()
>>> a.__lt__( b )
NotImplemented
>>> if a.__lt__( b ):
... print( "derp!" )
...
derp
>>> if b.__lt__(a):
... print( "derp" )
...
derp
Here are some more references:
EDIT:
After taking a look at Python 2.7, it looks like the ID of the objects is used for sorting, and the __lt__ method is undefined on a simple class like your example. Sorry for any confusion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With