PYTHON Contents

Ordering and functools.total_ordering

Implement ordering safely using total_ordering, define a single source of truth, and avoid inconsistent comparisons.

On this page

Ordering Requires a Clear Definition

Ordering is easy to get wrong. Define one canonical comparison key and build ordering from it.

Use total_ordering

from functools import total_ordering

@total_ordering
class Job:
    def __init__(self, priority: int, created_at_iso: str) -> None:
        self.priority = priority
        self.created_at_iso = created_at_iso

    def _key(self):
        return (self.priority, self.created_at_iso)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Job):
            return NotImplemented
        return self._key() == other._key()

    def __lt__(self, other: object) -> bool:
        if not isinstance(other, Job):
            return NotImplemented
        return self._key() < other._key()

Operational Checklist

  • Define a stable comparison key (tuple) and reuse it.
  • Ensure ordering is consistent with equality.
  • Return NotImplemented for incompatible types.

Failure Modes

  • Inconsistent ordering: sorting becomes unstable and hard to debug.
  • Mixed types: comparisons crash at runtime when unexpected objects appear.