What methods need to be overridden/implemented when making user-defined classes sortable and/or hashable in python?
What are the gotchas to watch out for?
I
There isn't any difference between Python 2 and 3.
For sortability:
You should define comparision methods. This makes your items sortable. Generally, you shouldn't prefer __cmp__().
I usually use functools.total_ordering decorator.
functools.total_ordering(cls) Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest. This simplifies the effort involved in specifying all of the possible rich comparison operations:
The class must define one of
__lt__(),__le__(),__gt__(), or__ge__(). In addition, the class should supply an__eq__()method.
You should be careful that your comparison methods do not have any side effects. (change any of the values of the object)
For hashing:
You should implement __hash__() method. I think the best way is returning hash(repr(self)), so your hash would be unique.