Python functools.total_orderingの使い方|__eq__と__lt__だけで比較演算子を全部使う(NotImplemented・速度・dataclassとの違い)
@functools.total_orderingは、クラスに__eq__と__lt__(または__le__・__gt__・__ge__のどれか1つ)を書くだけで、残りの比較演算子<=・>・>=を自動で作ってくれるクラスデコレータです。
この記事では、total_orderingの書き方と、実際にどのメソッドが追加されるのか、__eq__を忘れたときや別の型と比べたときに起きること、NotImplementedの返し方、速度の差、@dataclass(order=True)との使い分けを、Python 3.12で実行した結果つきで解説します。仕様はPython公式ドキュメント(functools.total_ordering)に沿っています(2026年10月18日確認)。
total_orderingの使い方(基本の書き方)
from functools import total_ordering
@total_ordering
class クラス名:
def __eq__(self, other): ... # == の定義
def __lt__(self, other): ... # < の定義(<= > >= のどれでもよい)
| 項目 | 内容 |
|---|---|
| 付ける場所 | クラス定義の直前(クラスデコレータ) |
| 必須 | __lt__・__le__・__gt__・__ge__のうち1つ以上 |
| 書くべきもの | __eq__(公式ドキュメントでも用意するよう求められている) |
| 追加されるもの | 足りない比較メソッド(__eq__は追加されない) |
| 使えるバージョン | Python 3.2以降 |
total_orderingがないと<=が使えない
例として、"1.9.2"や"1.10.0"のようなバージョン番号を比べるクラスを作ります。文字列のまま比べると"1.9.2" < "1.10.0"はFalseになってしまうので、数字のタプルに直して比べます。
class Version:
def __init__(self, s):
self.parts = tuple(int(x) for x in s.split("."))
def __eq__(self, other):
return self.parts == other.parts
def __lt__(self, other):
return self.parts < other.parts
a, b = Version("1.9.2"), Version("1.10.0")
print(a < b, a == b)
print(a <= b)
実行結果:
True False
TypeError: '<=' not supported between instances of 'Version' and 'Version'
<は動くのに<=はエラーです。Pythonは演算子ごとに別のメソッドを呼ぶため、書いていないメソッドの演算子は使えません。
| 演算子 | 呼ばれるメソッド | total_orderingで |
|---|---|---|
== |
__eq__ |
自分で書く |
!= |
__ne__ |
Pythonが__eq__の反対を自動で返す(もともと不要) |
< |
__lt__ |
自分で書く(例) |
<= |
__le__ |
自動で追加 |
> |
__gt__ |
自動で追加 |
>= |
__ge__ |
自動で追加 |
@total_orderingを付けると全部の比較が使える
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, s):
self.s = s
self.parts = tuple(int(x) for x in s.split("."))
def __eq__(self, other):
return self.parts == other.parts
def __lt__(self, other):
return self.parts < other.parts
def __repr__(self):
return f"Version('{self.s}')"
a, b = Version("1.9.2"), Version("1.10.0")
print(a < b, a <= b, a > b, a >= b, a == b, a != b)
print("1.9.2" < "1.10.0")
print(sorted([Version("2.0"), Version("1.10.0"), Version("1.9.2")]))
print(max(Version("2.0"), Version("1.10.0")))
実行結果:
True True False False False True
False
[Version('1.9.2'), Version('1.10.0'), Version('2.0')]
Version('2.0')
クラスの上に1行足しただけで、6種類の比較がすべて動きました。2行目は文字列のまま比べた結果で、"1.9.2" < "1.10.0"がFalseになる(1文字ずつ比べるため)ことが、自作クラスで比較を定義する理由になっています。
どのメソッドが追加されたか確かめる
print([m for m in ("__lt__", "__le__", "__gt__", "__ge__") if m in Version.__dict__])
print(Version.__le__)
実行結果:
['__lt__', '__le__', '__gt__', '__ge__']
<function _le_from_lt at 0x10570bce0>
__lt__以外の3つがクラスに追加されています。_le_from_ltという名前のとおり、<=は自分で書いた<(と==)の結果から計算されます(アドレスの数字は実行ごとに変わります)。
比較メソッドが1つもないとValueError
from functools import total_ordering
@total_ordering
class Empty:
pass
実行結果:
ValueError: must define at least one ordering operation: < > <= >=
エラーはインスタンスを作ったときではなく、クラスを定義した時点で出ます。__eq__だけ書いた場合も同じエラーになります。
__eq__を忘れるとエラーにならずに結果がおかしくなる
from functools import total_ordering
@total_ordering
class Person:
def __init__(self, age):
self.age = age
def __lt__(self, other):
return self.age < other.age
print(Person(1) == Person(1))
print(Person(1) <= Person(1))
実行結果:
False
False
同じ年齢なのに==も<=もFalseです。__eq__がないと、既定の「同じオブジェクトかどうか」の判定が使われ、さらに自動生成された<=(「<または==」で計算)まで巻き込まれます。total_orderingは__eq__を作らないので、必ず自分で書いてください。__eq__の書き方は「Python __eq__とは?」で解説しています。
別の型と比べるときはNotImplementedを返す
上の例のようにother.partsをいきなり読むと、数値など別の型と比べたときに分かりにくいエラーになります。公式ドキュメントの例と同じく、扱えない相手にはNotImplementedを返すのが正しい書き方です(Python 3.4以降、total_orderingはこれに対応しています)。
from functools import total_ordering
@total_ordering
class Bad:
def __init__(self, n): self.n = n
def __eq__(self, other): return self.n == other.n
def __lt__(self, other): return self.n < other.n
@total_ordering
class Good:
def __init__(self, n): self.n = n
def __eq__(self, other):
if not isinstance(other, Good):
return NotImplemented
return self.n == other.n
def __lt__(self, other):
if not isinstance(other, Good):
return NotImplemented
return self.n < other.n
for cls in (Bad, Good):
try:
print(cls(1) >= 5)
except Exception as e:
print(cls.__name__, type(e).__name__, e)
print(Good(1) == 5)
実行結果:
Bad AttributeError 'int' object has no attribute 'n'
Good TypeError '>=' not supported between instances of 'Good' and 'int'
False
Badは「intにnがない」という本題と関係のないエラーになりますが、Goodは「この組み合わせは比べられない」という正しいTypeErrorになります。==のほうはNotImplementedを返すとPythonが既定の判定に切り替えるため、エラーではなくFalseになります。
親クラスにある比較メソッドは上書きされない
公式ドキュメントの注意書きにあるとおり、total_orderingはクラス自身や親クラスにすでにある比較メソッドを作り直しません。
from functools import total_ordering
class Base:
def __le__(self, other):
return False # 親クラスの(未完成の)実装
@total_ordering
class Score(Base):
def __init__(self, n): self.n = n
def __eq__(self, other): return self.n == other.n
def __lt__(self, other): return self.n < other.n
print(Score(1) < Score(3))
print(Score(1) <= Score(3))
print(Score.__le__ is Base.__le__)
実行結果:
True
False
True
<は正しいのに<=は親クラスの実装のまま残り、誤った結果になりました。継承を使うときは、親クラスにどの比較メソッドがあるかを先に確認してください。
速度:自動生成のぶん遅くなる
自動生成された演算子は、自分で書いた演算子を呼び出してから結果を組み立てるため、直接書いたメソッドより遅くなります。a >= bを100万回実行して比べました(5回測った最小値)。
import timeit
from functools import total_ordering
@total_ordering
class A:
__slots__ = ("n",)
def __init__(self, n): self.n = n
def __eq__(self, o): return self.n == o.n
def __lt__(self, o): return self.n < o.n
class B:
__slots__ = ("n",)
def __init__(self, n): self.n = n
def __eq__(self, o): return self.n == o.n
def __lt__(self, o): return self.n < o.n
def __le__(self, o): return self.n <= o.n
def __gt__(self, o): return self.n > o.n
def __ge__(self, o): return self.n >= o.n
a1, a2, b1, b2 = A(1), A(2), B(1), B(2)
for name, stmt in [("total_ordering", "a1 >= a2"), ("手書き", "b1 >= b2")]:
t = min(timeit.repeat(stmt, globals=globals(), number=1_000_000, repeat=5))
print(f"{name}: {t:.3f}秒 / 100万回")
実行結果(Apple Silicon搭載Mac・Python 3.12):
total_ordering: 0.073秒 / 100万回
手書き: 0.037秒 / 100万回
この環境では約2倍の時間がかかりましたが、1回あたりでは0.1マイクロ秒に満たない差です。公式ドキュメントも、処理が遅くなることとエラー時のトレースバックが長くなることを注意点に挙げ、計測してボトルネックだと分かった場合は6つすべてを手で書けば速くなる、としています。ふだんはtotal_orderingで書き、遅さが測れたときだけ手書きに替えるのが現実的です。
sorted()だけなら__lt__だけで足りる
sorted()・list.sort()・min()・max()は<しか使いません。並べ替えだけが目的なら__lt__を書けば十分で、total_orderingは不要です。並べ替えのための__lt__の書き方は「Python __lt__とは?自作クラスをsorted()で並べ替える方法」で解説しています。total_orderingが役立つのは、バージョン番号・日付・優先度・ランクのように、コードのあちこちで>=や<=を書きたいクラスです。
@dataclass(order=True)との使い分け
フィールドを定義順に比べるだけなら、dataclassのほうが短く書けます。
from dataclasses import dataclass, field
@dataclass(order=True)
class Person:
age: int
name: str = field(compare=False)
print(Person(20, "佐藤") < Person(30, "鈴木"))
print(Person(20, "佐藤") <= Person(20, "田中"))
実行結果:
True
True
| こんなとき | 選ぶもの |
|---|---|
| フィールドを定義順にそのまま比べればよい | @dataclass(order=True) |
| 比べ方を自分で決めたい(大文字小文字を無視、文字列を数値に直すなど) | @total_ordering |
| 既存のクラスに比較を後から足したい | @total_ordering |
| 大量の比較で速度が重要 | 6つの比較メソッドを手書き |
order=Trueの細かい挙動は「Python dataclassのorder=Trueの使い方」をご覧ください。
よくある質問
Q. total_orderingには何を定義すればよいですか?
__eq__と、__lt__・__le__・__gt__・__ge__のうちどれか1つです。比較メソッドが1つもないとクラスを定義した時点でValueErrorになります。__eq__は自動で作られないので必ず書きます。
Q. __lt__ではなく__gt__を書いてもよいですか?
はい。__lt__・__le__・__gt__・__ge__のどれを基準にしても、残りが自動で追加されます。
Q. 別の型と比べたときのエラーを正しく出すには?
__eq__や__lt__の中で相手の型を確認し、扱えない場合はNotImplementedを返します。そうするとPythonが「比べられない」というTypeErrorを出してくれます。
Q. total_orderingを使うと遅くなりますか?
自動生成された演算子は自分で書いた演算子を経由するため遅くなります。この記事の計測では約2倍でしたが、1回あたりの差はごくわずかです。速度が問題になると計測で分かったときだけ、6つすべてを手で書きます。
functools.total_orderingのまとめ
@total_orderingは足りない比較演算子を自動で追加するクラスデコレータ- 書くのは
__eq__と、<・<=・>・>=のどれか1つ - 比較メソッドがないと
ValueError、__eq__を忘れるとエラーなしで誤動作 - 別の型には
NotImplementedを返す。親クラスにある比較メソッドは上書きされない - 少し遅くなる。フィールド順の比較で足りるなら
@dataclass(order=True)



