Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

functools.total_ordering

Synthesizes missing ordering methods from equality and one supplied ordering comparison.

Version: Python 3.14; repository image, production runtime not attested

Syntax

@functools.total_ordering

Synthesizes missing ordering methods from equality and one supplied ordering comparison.

Use consistent equality and ordering definitions. Supporting an unrelated type requires a deliberate cross-type comparison policy.

Provide one ordering method such as __lt__ plus meaningful __eq__ to derive the missing ordering methods. Existing methods, including inherited ones, are not replaced. Returning NotImplemented for unsupported types allows reflected comparison or TypeError. In the sample equal ranks satisfy >= while rank 1 is not greater than 3. Generated comparisons may add calls and stack frames relative to implementing all six comparison methods directly.

from functools import total_ordering
@total_ordering
class Level:
    def __init__(self, n): self.n = n
    def __eq__(self, other): return self.n == other.n if isinstance(other, Level) else NotImplemented
    def __lt__(self, other): return self.n < other.n if isinstance(other, Level) else NotImplemented
assert Level(2) >= Level(2) and Level(3) > Level(2)
try:
    Level(1) < 2
except TypeError:
    pass
else:
    raise AssertionError
assert Level.__lt__(Level(2), "x") is NotImplemented

Examples

import functools
@functools.total_ordering
class Rank:
    def __init__(self, value): self.value = value
    def __eq__(self, other): return self.value == other.value if isinstance(other, Rank) else NotImplemented
    def __lt__(self, other): return self.value < other.value if isinstance(other, Rank) else NotImplemented

print(Rank(2) >= Rank(2), Rank(1) > Rank(3))

Result

True False

Provide one ordering method such as `__lt__` plus meaningful `__eq__` to derive the missing ordering methods. Existing methods, including inherited ones, are not replaced. Returning NotImplemented for unsupported types allows reflected comparison or TypeError. In the sample equal ranks satisfy >= while rank 1 is not greater than 3. Generated comparisons may add calls and stack frames relative to implementing all six comparison methods directly.

Sources