Making a python user-defined class sortable, hashable

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)