Python Glossary Русский

all Python 3functoolsterm

functools.total_ordering

comparison

A class decorator. Given __eq__ and at least one ordering method, it fills in the missing comparison operators (<, <=, >, >=).

Syntax

@functools.total_ordering

Defining __eq__ wipes out the inherited __hash__, so instances stop being hashable — total_ordering does not restore it, you have to set __hash__ yourself. The generated operators are thin wrappers that call your __eq__ and __lt__, so they run noticeably slower than hand-written ones and clutter tracebacks; on a hot path just write all six. Also make __lt__ return NotImplemented for unrelated types, otherwise comparing against a foreign object blows up with AttributeError instead of a clean TypeError.

Examples

from functools import total_ordering
@total_ordering
class Version:
    def __init__(self, v): self.v = v
    def __eq__(self, o): return self.v == o.v
    def __lt__(self, o): return self.v < o.v
v1, v2 = Version(1), Version(2)
print(v1 < v2)  # → True
print(v1 > v2)  # → False
print(v1 <= v1)  # → True
print(v2 >= v1)  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy