Python total_ordering 实战:用 12 组测试划清比较、相等与哈希边界
写一个按“优先级、入队序号”排序的任务对象时,往往只想维护一份比较规则。functools.total_ordering 可以减少重复方法,但类型能比较、对象相等、对象能作为字典键,是三个需要分别作出决定的问题。本文用一个完整文件和 12 组 unittest 测试,把这几个边界实际跑出来。
实测环境为 CPython 3.12.14,分别使用普通模式和 -O 模式。核验日期为北京时间 2026 年 10 月 21 日;所引用的 Python 3.12 在线文档当日页面标题为 3.12.15,不等同于本次运行的解释器版本。本文没有运行性能基准,也没有把测试样例通过宣称为任意输入的全序证明。

一、先确定比较域,再使用装饰器
示例 QueueEntry 的业务约定很具体:
priority 越小越靠前;优先级相同时,再比较 sequence。
相等和排序都使用同一份二元组 key()。label 只是展示文字,因此同键、不同 label 的两个对象按本例约定相等。
根方法只接受与自身运行时类型完全相同的对象。对于其他类型返回 NotImplemented,而不是自行转换字符串、数字或别人的对象。
构造时只接受真正的 int,排除 bool、float、NaN 和字符串。对象仍然可变,构造校验不会拦截后续直接改属性;以下测试没有覆盖任意修改后的状态。不要在排序或优先队列使用期间修改排序键;这不是生产级的完整状态封装。
这些是示例的策略,不是 Python 要求所有类照做。尤其需要分清“同一个任务实体”和“具有相同比较键”:如果业务要求 label 或任务 ID 参与相等判断,就必须重新设计排序键和等价关系,不能只改 __eq__ 一处。
装饰器要求类至少提供 __lt__、__le__、__gt__、__ge__ 中的一个排序方法,并建议提供 __eq__。本文提供 __lt__ 与 __eq__,让它补齐其余排序方法;它不会替换类及其父类已有的比较实现。官方 total_ordering 文档说明了这些条件。
二、NotImplemented 是交还处理机会
直接调用 entry.__lt__(other) 与计算 entry < other 不是同一个观察层次。前者只调用一个方法,可能拿到 NotImplemented;后者由 Python 执行整个运算符分派,可能继续调用对方的反向比较方法。
对于没有继承优先级关系的两个类型,本例的 entry < peer 会先试 entry.__lt__(peer),收到 NotImplemented 后再试 peer.__gt__(entry)。小于与大于互为反向操作,小于等于与大于等于互为反向操作;并不存在 __rlt__ 这样的比较方法。若右操作数是左操作数类型的真子类,其反向方法有优先机会,因此不能把“左边永远先运行”当作通则。详见数据模型的富比较协议。
方法返回 False:该方法已经给出比较结果,当前分派不会因为结果是假而继续寻求另一方。
方法返回 NotImplemented:当前方法不处理这对操作数,允许协议继续寻找处理者。
方法抛出 NotImplementedError:这是异常,不是交还处理机会的信号。本例中异常直接传播,反向方法没有接着执行。
当双方都无法处理时,本例的排序表达式抛出 TypeError;相等和不等则有对象身份兜底,所以这些不同对象的 == 为 False、!= 为 True。不要把“返回 NotImplemented”写成“所有比较最终都会抛异常”,也不要把它放进 if 或 bool() 判断。内置常量文档特别区分了这个单例值与 NotImplementedError。
三、完整可运行文件
把下面整段保存为 total_ordering_demo.py。只使用标准库,不需要安装依赖;所有测试检查使用 unittest 的断言方法,没有依赖会被 -O 移除的裸 assert 语句。
from functools import total_ordering
import operator
import platform
import sys
import unittest
@total_ordering
class QueueEntry:
def __init__(self, priority, sequence, label=''):
for name, value in (('priority', priority), ('sequence', sequence)):
if type(value) is not int:
raise TypeError(f'{name} must be an int, not bool or float')
self.priority = priority
self.sequence = sequence
self.label = label
def key(self):
return (self.priority, self.sequence)
def __eq__(self, other):
if type(other) is not type(self):
return NotImplemented
return self.key() == other.key()
def __lt__(self, other):
if type(other) is not type(self):
return NotImplemented
return self.key() < other.key()
ORDER_OPS = (operator.lt, operator.le, operator.gt, operator.ge)
ALL_OPS = ORDER_OPS + (operator.eq, operator.ne)
class OrderingTests(unittest.TestCase):
def test_01_equality_policy_ignores_label(self):
a = QueueEntry(1, 2, 'original')
b = QueueEntry(1, 2, 'renamed')
self.assertIsNot(a, b)
self.assertIs(a == b, True)
self.assertIs(a != b, False)
self.assertIs(a <= b, True)
self.assertIs(a >= b, True)
def test_02_six_operators_match_tuple_keys(self):
keys = [(-1, 8), (0, 0), (0, 2), (1, -3)]
for left in keys:
for right in keys:
for op in ALL_OPS:
with self.subTest(left=left, right=right, op=op.__name__):
self.assertIs(
op(QueueEntry(*left), QueueEntry(*right)),
op(left, right),
)
def test_03_sorting_ties_and_extrema(self):
entries = [QueueEntry(2, 0, 'low'), QueueEntry(1, 2, 'tie-a'),
QueueEntry(1, 1, 'first'), QueueEntry(1, 2, 'tie-b')]
ordered = sorted(entries)
self.assertEqual([x.label for x in ordered],
['first', 'tie-a', 'tie-b', 'low'])
self.assertIs(min(entries), entries[2])
self.assertIs(max(entries), entries[0])
def test_04_direct_methods_return_not_implemented(self):
entry = QueueEntry(1, 0)
for other in (1, '1', None, object()):
for name in ('__eq__', '__lt__', '__le__', '__gt__', '__ge__'):
with self.subTest(other=type(other).__name__, method=name):
self.assertIs(getattr(entry, name)(other), NotImplemented)
def test_05_unsupported_expressions_are_not_sentinel_results(self):
entry = QueueEntry(1, 0)
for other in (1, '1', None, object()):
for left, right in ((entry, other), (other, entry)):
self.assertIs(left == right, False)
self.assertIs(left != right, True)
for op in ORDER_OPS:
with self.subTest(other=type(other).__name__, op=op.__name__):
with self.assertRaises(TypeError):
op(left, right)
def test_06_reflected_operand_can_accept(self):
calls = []
class Peer:
def __gt__(self, other):
calls.append('__gt__')
return True
def __ge__(self, other):
calls.append('__ge__')
return True
def __eq__(self, other):
calls.append('__eq__')
return True
entry, peer = QueueEntry(1, 0), Peer()
self.assertIs(entry < peer, True)
self.assertIs(entry <= peer, True)
self.assertIs(entry == peer, True)
self.assertEqual(calls, ['__gt__', '__ge__', '__eq__'])
def test_07_false_and_exception_stop_this_fallback(self):
calls = []
class Peer:
def __gt__(self, other):
calls.append('reflected')
return True
class SaysFalse:
def __lt__(self, other):
return False
class RaisesInstead:
def __lt__(self, other):
raise NotImplementedError('not a protocol sentinel')
self.assertIs(SaysFalse() < Peer(), False)
with self.assertRaises(NotImplementedError):
RaisesInstead() < Peer()
self.assertEqual(calls, [])
def test_08_base_and_subclass_are_not_interchangeable(self):
class Child(QueueEntry):
pass
base, child = QueueEntry(1, 0), Child(1, 0)
self.assertIs(base == child, False)
self.assertIs(child == base, False)
self.assertIs(child == Child(1, 0), True)
for left, right in ((base, child), (child, base)):
for op in ORDER_OPS:
with self.assertRaises(TypeError):
op(left, right)
def test_09_orderability_does_not_create_hashability(self):
a, b = QueueEntry(1, 0, 'a'), QueueEntry(1, 0, 'b')
self.assertIs(QueueEntry.__hash__, None)
with self.assertRaises(TypeError):
hash(a)
with self.assertRaises(TypeError):
{a: 'value'}
self.assertEqual(hash(a.key()), hash(b.key()))
self.assertEqual({a.key(): 'value'}[b.key()], 'value')
def test_10_decorator_requirements_and_inherited_methods(self):
class EqualityOnly:
def __eq__(self, other):
return self is other
with self.assertRaises(ValueError):
total_ordering(EqualityOnly)
class Base:
def __le__(self, other):
return False
@total_ordering
class KeepsInherited(Base):
def __eq__(self, other):
return self is other
def __lt__(self, other):
return False
self.assertIs(KeepsInherited.__le__, Base.__le__)
item = KeepsInherited()
self.assertIs(item <= item, False)
def test_11_constructor_rejects_unsupported_key_types(self):
for bad in (True, False, 1.0, float('nan'), '1', None):
for args in ((bad, 0), (0, bad)):
with self.subTest(args=args):
with self.assertRaises(TypeError):
QueueEntry(*args)
def test_12_inconsistent_keys_are_not_repaired(self):
@total_ordering
class WrongKey:
def __init__(self, priority, label):
self.priority, self.label = priority, label
def __eq__(self, other):
if type(other) is not type(self):
return NotImplemented
return (self.priority, self.label) == (other.priority, other.label)
def __lt__(self, other):
if type(other) is not type(self):
return NotImplemented
return self.priority < other.priority
a, b = WrongKey(1, 'a'), WrongKey(1, 'b')
self.assertIs(a == b, False)
self.assertIs(a < b, False)
self.assertIs(b < a, False)
self.assertIs(a > b, True)
self.assertIs(b > a, True)
self.assertIs(a <= b, False)
if __name__ == '__main__':
print(f'{platform.python_implementation()} {platform.python_version()} '
f'optimize={sys.flags.optimize}', flush=True)
unittest.main(verbosity=2)四、运行命令与实际结果
在文件所在目录执行以下两条命令。第二条的 -O 是解释器参数,放在文件名前:
python total_ordering_demo.py python -O total_ordering_demo.py
两次实际运行都完成 12 个 test 方法,退出码均为 0。下面摘录各次日志中的版本行与末尾汇总;中间 12 项逐项结果均为 ok:
CPython 3.12.14 optimize=0 Ran 12 tests in 0.003s OK CPython 3.12.14 optimize=1 Ran 12 tests in 0.004s OK
这里的耗时只是本次 unittest 输出,不能用于比较两种模式快慢。-O 会移除裸 assert;本文件使用 assertIs、assertEqual、assertRaises 等 unittest 方法,测试在优化模式下仍然实际执行。参数行为见Python -O 文档,断言方式见unittest 官方示例说明。
五、12 组测试各自守住什么
相等策略:同键不同 label 的对象相等,但不是同一个对象;相等时两边的非严格排序也成立。
六种运算符:4 个样本键两两组合,用 6 种操作与原始二元组结果对照,共检查 96 种组合。它是有限样本回归,不是形式证明。
排序与极值:检查优先级、序号、同键输入的顺序,以及 min、max 的实际返回对象。
直接方法调用:检查根方法和派生方法面对 4 类不支持对象都返回同一个 NotImplemented 单例。
表达式结果:分别检查左右两个方向,相等比较给出布尔结果,4 种排序比较抛出 TypeError。
反向接管:Peer 接管大于、大于等于和相等,调用记录验证协议确实走到了对方,而非凭空把不支持操作当作 False。
拒绝信号区别:返回 False 或抛出 NotImplementedError 时,本例的反向方法都没有被调用。
继承边界:基类与未改写方法的子类不互认;同一种子类的实例仍能互比。新增子类字段的语义不由装饰器自动决定。
哈希边界:对象能排序,但 hash(entry) 和把对象作为字典键都会失败;整数二元组键可单独用于字典。
装饰器边界:只有相等方法的类无法获得排序补全;父类已有的 __le__ 即使与其他方法不协调,也被原样保留。
输入范围:构造时拒绝布尔值、浮点数、NaN、字符串及 None,两个键字段都检查。
不一致反例:故意让排序忽略 label、相等却包含 label,观察装饰器不会修复矛盾。
unittest 报告的是 12 个测试方法,不把每个 subTest 另算成独立测试数量。第三组同键输入顺序保持,属于本次 sorted 调用的验证,也不意味着可以从 total_ordering 推出所有下游算法的行为。
六、为什么“双向大于”能同时为真
最后一组 WrongKey 的两个对象具有相同 priority、不同 label。因为 __lt__ 只看 priority,两个方向的小于都为 False;因为 __eq__ 还看 label,相等也为 False。本次实测中,补出来的大于比较竟在两个方向都为 True。这段反例用测试确认的是“错误仍然存在”,并不是推荐这样定义比较。
修正需要从业务含义入手:如果同优先级任务仍要有固定次序,就把明确的序号或标识纳入同一套比较键;如果只想临时按优先级展示,可把“展示排序”独立成 sorted(..., key=...),不要为了省几行代码去改变对象本身的相等语义。装饰器没有检查任意三元组的传递性,也没有证明你的字段域排除了所有不可比值。
七、可以排序,不代表可以进 set 或当字典键
QueueEntry 定义了 __eq__,没有定义 __hash__,因此 __hash__ 被置为 None。total_ordering 没有改变这一点。对于本例这种比较字段还可能变化的对象,保持不可哈希比直接恢复 object.__hash__ 更合适;相等对象若可哈希,必须有相同哈希值。该要求见官方 __hash__ 协议。
测试使用 a.key() 返回的整数二元组作为另一种字典键,含义是按当时的 priority、sequence 快照查找。它不是自动跟随对象更新的引用;后续改动对象,不会修改已经放进字典的元组。若系统同时存放多种任务子类,还需自行决定键中是否加入类型或命名空间。
将这份代码迁移到实际项目时,优先保留四条回归线:相等与排序是否来自同一业务约定,未知类型是否正确交还分派,继承方法是否意外抢占补全位置,以及比较字段变化时哈希策略是否仍然成立。先把这些决定写清楚,再让装饰器减少重复代码。

