← Back to Python, page 5

python-0085 · Medium mid

Make custom objects sortable and comparable with total_ordering and sort keys.

Define __eq__ and __lt__, then functools.total_ordering fills in <=, > and >=. Often a sort key is simpler: sorted(items, key=attrgetter('a', 'b')) needs no methods at all. Return NotImplemented for unsupported types so Python can try the other operand.

Full answer
python
from functools import total_ordering
from operator import attrgetter

@total_ordering
class Version:
    def __init__(self, text):
        self.parts = tuple(int(p) for p in text.split("."))
    def __eq__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return self.parts == other.parts
    def __lt__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return self.parts < other.parts
    def __hash__(self):
        return hash(self.parts)
    def __repr__(self):
        return ".".join(map(str, self.parts))

vs = [Version(v) for v in ["1.10.0", "1.2.3", "1.9", "2.0"]]
print(sorted(vs), max(vs), Version("1.9") >= Version("1.10.0"))
print(sorted(["1.10.0", "1.2.3", "1.9"]))
try:
    Version("1.0") < "1.0"
except TypeError as e:
    print("TypeError:", e)

Output:

text
[1.2.3, 1.9, 1.10.0, 2.0] 2.0 False
['1.10.0', '1.2.3', '1.9']
TypeError: '<' not supported between instances of 'Version' and 'str'

Comparing tuples of integers sorts versions numerically, so 1.10.0 comes after 1.9, while plain string sorting puts '1.10.0' first. total_ordering derives >= from __lt__ and __eq__. Returning NotImplemented for a string makes Python raise a clear TypeError instead of silently returning False. Defining __eq__ removes the default hash, so __hash__ is restored from the same tuple to keep versions usable in sets.

python
from functools import total_ordering
from operator import attrgetter

@total_ordering
class Version:
    def __init__(self, text):
        self.parts = tuple(int(p) for p in text.split("."))
    def __eq__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return self.parts == other.parts
    def __lt__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return self.parts < other.parts
    def __hash__(self):
        return hash(self.parts)
    def __repr__(self):
        return ".".join(map(str, self.parts))

vs = [Version(v) for v in ["1.10.0", "1.2.3", "1.9", "2.0"]]
print(sorted(vs), max(vs), Version("1.9") >= Version("1.10.0"))
print(sorted(["1.10.0", "1.2.3", "1.9"]))
try:
    Version("1.0") < "1.0"
except TypeError as e:
    print("TypeError:", e)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Define __eq__ and __lt__
  • total_ordering fills in the rest
  • Return NotImplemented for other types
  • Tuples compare element by element
  • Sort keys avoid methods altogether

Common mistakes

  • Sorting version strings lexically
  • Forgetting __hash__ after defining __eq__

Follow-ups

  • How would dataclass(order=True) do this?
  • How do you sort descending by one key and ascending by another?

Tips

  • Compare with string sorting