Total Ordering From One Comparison

Derive every rich comparison from __eq__ and __lt__ with functools.total_ordering, so sorting, min, and max work without boilerplate.

PythonData Integrity

Code

pythonsnippet
25 lines
from functools import total_ordering


@total_ordering  # 只写 __eq__ 与 __lt__,其余比较运算自动补全
class Version:
    def __init__(self, raw: str) -> None:
        self.parts = tuple(int(part) for part in raw.split('.'))

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

    def __lt__(self, other: 'Version') -> bool:
        return self.parts < other.parts

    def __repr__(self) -> str:
        return 'Version(' + '.'.join(map(str, self.parts)) + ')'


versions = [Version('1.10.0'), Version('1.2.3'), Version('2.0.0'), Version('1.2.3')]
print('sorted:', sorted(versions))
print('max:', max(versions))
print('<= works:', Version('1.2.3') <= Version('1.2.3'))
print('> works:', Version('2.0.0') > Version('1.10.0'))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

sorted: [Version(1.2.3), Version(1.2.3), Version(1.10.0), Version(2.0.0)]
max: Version(2.0.0)
<= works: True
> works: True

What the code does

Total Ordering From One Comparison keeps everything in the class Version and the functions __init__, __eq__, __lt__ and __repr__.

Applying it

The primary signature is def __init__(self, raw: str) -> None

The demo output is labeled (sorted:, max:, <= works:), so every printed line maps back to its originating operation.

Statements that matter

def __init__(self, raw: str) -> None:
    self.parts = tuple(int(part) for part in raw.split('.'))
def __lt__(self, other: 'Version') -> bool:
    return self.parts < other.parts
def __eq__(self, other: object) -> bool:
    if not isinstance(other, Version):
        return NotImplemented
    return self.parts == other.parts

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `functools`. The file defines `__init__`, `__eq__`, `__lt__` at load time.