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.
Code
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: TrueWhat 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
JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.