Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting class instances in python

Tags:

python

sorting

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:

  • Is python using the objects' __hash__(), and thus their id()?
  • Is it possible to override __hash__() to influence the sorting behavior?
like image 346
noio Avatar asked Aug 25 '26 06:08

noio


1 Answers

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:

  • The __lt__ method (Unofficial Python Reference Wiki)
  • Sorting Mini How-To
  • Built-In Constants

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.

like image 198
derekerdmann Avatar answered Aug 27 '26 20:08

derekerdmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!