There is a functools
built-in method total_ordering
that can decorate your class and enable its instances to be passed to sorted() without a key function specification.
The only requirements for the class is to define any of the comparison dunder methods and __eq__
.
E.g.:
from functools import total_ordering
@total_ordering
class Sortable:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return self.x, self.y
def __lt__(self, obj):
return self.y < obj.y
def __eq__(self, obj):
return self.y == obj.y
obj_1 = Sortable("Hello", 9)
obj_2 = Sortable("World", -2)
obj_3 = Sortable("!", 5.5)
print(sorted([obj_1, obj_2, obj_3])
Which outputs:
>>> [("World", -2), ("!", 5.5), ("Hello", 9)]
sorted()
implemented viasort()
? – Oviduct