functools.total_ordering
Prev: functools.singledispatchmethod | Up: functools | Next: functools.update_wrapper
Rel: functools.cache, functools.cached_property, functools.cmp_to_key, functools.lru_cache
Ref: docs.python.org — functools.total_ordering
Tags: #public #python3 #stdlib #functools
Import
import functools
from functools import total_ordering
Signature & Overview
functools.total_ordering(cls)
Class decorator that fills in missing ordering methods
Usage
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major: int, minor: int) -> None:
self.key = (major, minor)
def __eq__(self, other: object) -> bool:
return isinstance(other, Version) and self.key == other.key
def __lt__(self, other: "Version") -> bool:
if not isinstance(other, Version):
return NotImplemented
return self.key < other.key
assert Version(1, 2) <= Version(1, 2) < Version(2, 0)
assert Version(2, 0) >= Version(1, 2)
Gotchas
- Must define
__eq__plus at least one of__lt__,__le__,__gt__,__ge__: OtherwiseValueErroris raised at class definition time. - Return
NotImplementedfor unknown types: Don't raiseTypeErrormanually in__lt__, or Python's reflected comparison fallback won't work. - Consider
@dataclass(order=True): For simple value classes,dataclassesgenerates all six comparison methods faster without@total_ordering's extra indirection.
REPL Inspect
from functools import total_ordering
help(total_ordering)
Linked from
Related notes
- tuts/python3/stdlib_module/functools/singledispatchmethod Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/update_wrapper Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/cache Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/cached_property Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/cmp_to_key Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/lru_cache Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/partial shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/partialmethod shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/reduce shared tags: #functools, #stdlib