← retour aux snippets

functools: total_ordering pour comparateurs

Implémenter __lt__/__eq__ et dériver le reste automatiquement.

objectif

Implémenter lt/eq et dériver le reste automatiquement.

code minimal

from dataclasses import dataclass
from functools import total_ordering

@total_ordering
@dataclass(frozen=True)
class Version:
    major:int; minor:int; patch:int=0
    def __lt__(self, other): return (self.major, self.minor, self.patch) < (other.major, other.minor, other.patch)
    def __eq__(self, other): return (self.major, self.minor, self.patch) == (other.major, other.minor, other.patch)

print(Version(1,2) < Version(1,2,1) and Version(1,2,1) >= Version(1,2,1))  # attendu: True

utilisation

print(True)

variante(s) utile(s)

from dataclasses import dataclass
from functools import total_ordering
@total_ordering
@dataclass(frozen=True)
class N: x:int
    # lt/eq implicites non définis ici -> incorrect en vrai
    def __lt__(self, o): return self.x < o.x
    def __eq__(self, o): return self.x == o.x
print(N(1) < N(2))

notes

  • total_ordering complète les autres comparateurs à partir de lt/eq.
  • Maintenez la cohérence transitive pour éviter des surprises.