Question
Asked By – Matt Fenwick
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 type dir({})
into my interpreter to get a list of methods on built-in dicts. Of those, I assume I need to some implement some subset of
['__cmp__', '__eq__', '__ge__', '__gt__', '__hash__', '__le__', '__lt__', '__ne__']
Is there a difference in which methods must be implemented for Python3 as opposed to Python2?
Now we will see solution for issue: Making a python user-defined class sortable, hashable
Answer
I almost posted this as a comment to the other answers but it’s really an answer in and of itself.
To make your items sortable, they only need to implement __lt__
. That’s the only method used by the built in sort.
The other comparisons or functools.total_ordering
are only needed if you actually want to use the comparison operators with your class.
To make your items hashable, you implement __hash__
as others noted. You should also implement __eq__
in a compatible way — items that are equivalent should hash the same.
This question is answered By – agf
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0