Sorting custom Python objects with __lt__ and __eq__

Sorting custom Python objects with __lt__ and __eq__

Make a Python class sortable with __lt__ and __eq__:

class C:
    def __init__(self, x):
        self.x = x
    def __lt__(self, o):
        return self.x < o.x
    def __eq__(self, o):
        return self.x == o.x
sorted([C(3), C(1), C(2)])  # orders by x: 1, 2, 3