Python 精确整数协议:分清 __index__、__int__ 与索引参数边界
int(x) 能成功,为什么 range(x) 或 items[x] 还会报错?这通常不是 Python 的不一致,而是两处接口要求不同。本文围绕 __index__ 与 __int__,从可执行反例出发,说明精确整数协议如何工作,以及怎样在自己的接口中保留类型、单位和范围边界。
下文八段代码都能分别保存为独立 Python 文件运行,只使用标准库,已经在 CPython 3.12.14 实测。版本变化会单独注明;不需要安装第三方数值库,也不依赖上一段代码里的类或变量。

一 先用反例分清转换和整数资格
处理页码、分片数量或数组位置时,很多函数先执行 int(value),再把结果交给后续逻辑。这看起来宽容,却把两个问题混在了一起:输入能否经过某种转换得到整数,以及输入是否已经具备整数语义。前者可能涉及截断、解析文本或者业务自定义规则;后者要求调用方能够把这个对象当作一个离散的整数值使用。参数名叫 count,并不能替你作出这项选择。
下面先从一个只定义 __int__ 的类入手。它支持显式转换,却不能直接充当列表下标。浮点数 3.0 虽然数值上等于整数,也不会因此取得索引资格;字符串 "3" 能被解析,同样不意味着字符串已经是整数。这里的拒绝是保留输入边界,而不是转换功能不够强。PEP 357 的设计理由正是要把整数身份与一般数值强制转换分开。
import operator
class IntOnly:
def __int__(self):
return 3
assert int(3.9) == 3
assert int(-3.9) == -3
assert int("3") == 3
assert int(IntOnly()) == 3
for value in (3.0, 3.9, "3", IntOnly()):
try:
operator.index(value)
except TypeError:
pass
else:
raise AssertionError("input must not qualify as an index")
try:
[10, 20, 30, 40][IntOnly()]
except TypeError:
pass
else:
raise AssertionError("__int__ alone must not enable indexing")
print("01 conversion and index protocol are distinct")尤其要记住负数的例子:int(-3.9) 得到 -3,采用朝零截断,并不是向下取整。把这样的转换藏在分页、采样或切片函数里,会悄悄改变调用者提交的请求。若业务确实允许取整,应当把规则写在接口说明和函数名称中;若业务要求精确的整数参数,就应该让小数和数字文本在入口失败。
二 用 __index__ 接入需要整数的操作
__index__ 是类型向 Python 声明整数语义的特殊方法。它必须产生整数结果。调用方通常使用 operator.index(value) 获取协议结果,而不是直接调用 value.__index__();这样做能走标准协议入口,也能得到返回值检查。在 Python 3.10 及以后的版本中,operator.index 的结果类型固定为内置 int。operator 官方文档记录了这个版本边界。
下例刻意要求构造器只接受普通 int,使示例不会在构造阶段偷偷截断浮点数。这里的 Ordinal 表示无单位的离散位置或边界,提供整数语义是有意的设计。它可以用于序列下标、切片边界、range 的参数,以及 bin、hex、oct。支持这些入口不代表它自动支持加法、排序或与整数相等;那些行为属于各自的协议。
import operator
class Ordinal:
def __init__(self, value):
if type(value) is not int:
raise TypeError("Ordinal requires a plain int")
self.value = value
def __index__(self):
return self.value
items = ["a", "b", "c", "d", "e"]
x = Ordinal(3)
assert operator.index(x) == 3
assert type(operator.index(x)) is int
assert items[x] == "d"
assert items[Ordinal(1):Ordinal(5):Ordinal(2)] == ["b", "d"]
assert list(range(Ordinal(1), Ordinal(6), Ordinal(2))) == [1, 3, 5]
assert bin(x) == "0b11"
assert hex(Ordinal(31)) == "0x1f"
assert oct(Ordinal(9)) == "0o11"
assert items[Ordinal(-1)] == "e"
assert not isinstance(x, int)
print("02 one exact integer protocol serves multiple consumers")负值是否允许,要由消费方决定。列表下标允许负数并从末尾解释,range 也允许负端点和负步长;但是业务中的重试次数通常不能为负。协议解决的是“怎样取得整数”,业务校验解决的是“这个整数在当前场景是否合法”。不要为了某个非负参数,就在所有可索引对象中一概禁止负数。range 的官方说明也明确要求其参数是整数或提供 __index__ 的对象。
三 int 的后备调用不能证明两个协议等价
一个容易产生误会的细节是:对象没有定义 __int__ 时,int 可以退回 __index__。于是只写 __index__ 的类往往也能被 int 转换。这条单向后备关系,并不意味着所有能传给 int 的对象都能用作下标。它也不意味着定义了两个方法之后,解释器会检查两者返回的数值是否一致。
下面的 SplitMeaning 故意给出不同结果,用来观察分派顺序,不是推荐的类设计。int 会选择 __int__,operator.index 则选择 __index__。另外,已存在的 __int__ 若返回非法类型,int 会报错,不会把失败悄悄当作“没有这个方法”,再去尝试 __index__。把这些行为做成断言,比仅凭方法名称理解后备关系更稳妥。
import operator
class IndexOnly:
def __index__(self):
return 7
class SplitMeaning:
def __int__(self):
return 70
def __index__(self):
return 7
class InvalidInt:
def __int__(self):
return "7"
def __index__(self):
return 7
assert int(IndexOnly()) == 7
assert operator.index(IndexOnly()) == 7
assert int(SplitMeaning()) == 70
assert operator.index(SplitMeaning()) == 7
assert operator.index(InvalidInt()) == 7
try:
int(InvalidInt())
except TypeError:
pass
else:
raise AssertionError("an invalid __int__ is not an absent method")
print("03 fallback is directional and does not hide invalid returns")实务上,如果对象承诺整数身份,就应当让有关的整数表示保持一致,避免日志中 int(x) 显示一个值,实际索引却落到另一个位置。需要“显示编号”和“内部偏移”两种值时,给它们明确的属性或方法通常更清楚。本文脚本在 CPython 3.12.14 执行;int 文档说明了 __int__ 与 __index__ 的关系。较新的 Python 3.14 已移除 int 对 __trunc__ 的旧后备,因此新代码也不应借用那条路径。该变化已核对 3.14 官方文档,但本文没有声称在 3.14 运行测试。
四 切片对象的创建和整数校验发生在不同层
看到 slice(1.5, 4) 能成功创建,不能得出“切片允许浮点数”的结论。slice 可以先保存起点、终点和步长,具体容器消费这个切片时才解释这些字段。普通列表在使用浮点边界时会拒绝它;调用 slice.indices(length) 也会进行适用于序列的边界规范化和检查。
还有一个常被省略的边界:方括号语法本身不保证把键统一转换成整数。自定义容器的 __getitem__ 可以收到原来的对象或 slice,并自行决定语义。字典按键查找,也不是这里讨论的序列位置协议。若你正在写容器,就需要明确转发给内置序列,或者自己调用 operator.index、处理切片;不能假定解释器已经替你把所有输入清洗好了。
class Position:
def __init__(self, value):
self.value = value
def __index__(self):
return self.value
items = list("abcdef")
part = slice(Position(1), Position(6), Position(2))
assert items[part] == ["b", "d", "f"]
assert part.indices(6) == (1, 6, 2)
assert slice(-100, 100, 1).indices(6) == (0, 6, 1)
bad = slice(1.5, 4)
assert bad.start == 1.5
for action in (lambda: items[bad], lambda: bad.indices(6)):
try:
action()
except TypeError:
pass
else:
raise AssertionError("sequence slicing must reject float bounds")
class EchoKey:
def __getitem__(self, key):
return key
key = Position(2)
assert EchoKey()[key] is key
assert EchoKey()[bad] is bad
print("04 slice storage and sequence interpretation are separate")下标越界和切片越界也不能混为一谈:内置列表的单个下标超出范围会报错,切片边界通常会按长度收缩;步长为零则不合法。这里的 indices 方法适合把切片规范化为可交给 range 的三个整数,而不是把所得三元组不加区分地重新拼成另一个切片。特别是反向切片,规范化后的负停止值与原始省略边界含义不同。slice.indices 的数据模型说明给出了方法用途。
五 非法返回值不会被递归修好
实现 __index__ 时,返回一个能够被 int 转换的对象仍然不够;返回另一个提供 __index__ 的包装器也不够。协议不会递归追着包装器找一个最终整数。字符串、浮点数、None 以及 NotImplemented 都不能作为这种方法的正常结果。NotImplemented 在部分二元运算协议中有特殊意义,却不是任意特殊方法通用的“请换条路径”信号。
同样,协议入口不会吞掉方法内部主动抛出的业务异常。若对象已经失效,内部抛出 RuntimeError 可以直接传到调用方。接口封装应尽量只改写自己真正负责的异常;为了给错误加一句统一提示就捕获所有 Exception,容易把实现缺陷伪装成普通输入错误,也让排查更困难。
import operator
class AnotherIndex:
def __index__(self):
return 2
class BadIndex:
def __init__(self, result):
self.result = result
def __index__(self):
return self.result
for result in (2.0, "2", None, NotImplemented, AnotherIndex()):
try:
operator.index(BadIndex(result))
except TypeError:
pass
else:
raise AssertionError("__index__ must directly produce an integer")
class Unavailable:
def __index__(self):
raise RuntimeError("index state is unavailable")
try:
operator.index(Unavailable())
except RuntimeError as exc:
assert str(exc) == "index state is unavailable"
else:
raise AssertionError("implementation errors must remain visible")
print("05 invalid protocol results fail instead of being coerced")写新类时,最稳妥的返回值是普通内置 int。不要让 __index__ 返回 bool 或 int 的自定义子类,再依赖某个解释器版本的兼容处理;旧版本可能接受并发出弃用警告,这不适合成为库的承诺。下节讨论“输入本身是 bool”的问题,它与“自定义方法返回 bool”是两个不同层次,测试时也应分开覆盖。
六 bool 是合法协议输入 但业务可以明确拒绝
Python 的 bool 是 int 的子类,所以 operator.index(True) 得到 1,False 得到 0。如果参数表示批次数、重试次数或预取数量,调用者把开关误传进来往往是错误,而不是希望发送一批请求。因此,仅使用 isinstance(value, int) 并不能排除布尔值;只允许 type(value) is int 又会排除原本合法的第三方整数类型。
一种实用策略是先拒绝直接传入的 bool,再用 operator.index 获取整数,最后检查业务范围。下面的函数接受正常整数及可靠的整数协议对象,拒绝浮点数和文本,同时设置上限,避免合法但极大的整数造成资源问题。转换只执行一次,后续检查和使用都基于同一个结果,避免有状态的 __index__ 在重复调用时给出不同值。
import operator
class TicketCount:
def __init__(self, value):
self.value = value
self.calls = 0
def __index__(self):
self.calls += 1
return self.value
def checked_count(value):
if isinstance(value, bool):
raise TypeError("count must not be a boolean")
count = operator.index(value)
if not 0 <= count <= 1000:
raise ValueError("count must be between 0 and 1000")
return count
assert operator.index(True) == 1
assert operator.index(False) == 0
assert isinstance(True, int)
x = TicketCount(3)
assert checked_count(x) == 3
assert x.calls == 1
assert checked_count(0) == 0
for value, error in ((True, TypeError), (False, TypeError),
(3.0, TypeError), ("3", TypeError),
(-1, ValueError), (1001, ValueError)):
try:
checked_count(value)
except error:
pass
else:
raise AssertionError("invalid count was accepted")
print("06 protocol acceptance and business constraints compose")这个策略只承诺拒绝入口处的布尔对象;它不是对任意对象的来源审计。如果某个包装器已经把 True 保存成整数 1,消费方通常无法再恢复原始输入。应当在最早还能辨识用户意图的边界检查类型,并把规范化后的值继续往下传。这也是配置解析、命令行参数处理和领域对象构造应各自负责一层校验的原因。
七 数量对象是否应该实现整数协议
运行时能够检查 __index__ 的返回值是不是整数,却不能证明实现者没有在方法内部截断小数或丢掉单位;“精确、无损”也是类型作者必须兑现的语义承诺。一个类内部存着整数,并不足以成为实现 __index__ 的理由。订单编号是整数,并不表示它适合充当列表位置;毫秒数是整数,也不表示它可以不经换算地充当帧数。实现这个协议会让对象进入多个标准接口,因此它是一项公开的语义承诺,而不只是让某行代码少写一个属性访问的快捷方式。
下面把离散行数与持续时间分开。RowCount 的设计就是一个非负、无单位歧义的行数,可以用于 range。Duration 保留秒这个单位,通过明确命名的 complete_frames 方法结合帧率转换,并清楚选择只计算完整帧。转换采用 Decimal 和向下取整,避免把 float 先转成 int 的隐含截断当成业务规范。持续时间本身没有 __index__,所以不会意外成为序列下标。
import operator
from dataclasses import dataclass
from decimal import Decimal, ROUND_FLOOR
@dataclass(frozen=True)
class RowCount:
value: int
def __post_init__(self):
if type(self.value) is not int:
raise TypeError("row count requires a plain int")
if self.value < 0:
raise ValueError("row count must be non-negative")
def __index__(self):
return self.value
@dataclass(frozen=True)
class Duration:
seconds: Decimal
def __post_init__(self):
if not isinstance(self.seconds, Decimal):
raise TypeError("seconds must be Decimal")
if not self.seconds.is_finite() or self.seconds < 0:
raise ValueError("seconds must be finite and non-negative")
def complete_frames(self, fps):
if type(fps) is not int:
raise TypeError("fps must be a plain int")
if fps <= 0:
raise ValueError("fps must be positive")
frames = self.seconds * fps
return int(frames.to_integral_value(rounding=ROUND_FLOOR))
assert list(range(RowCount(3))) == [0, 1, 2]
duration = Duration(Decimal("1.25"))
assert duration.complete_frames(10) == 12
try:
operator.index(duration)
except TypeError:
pass
else:
raise AssertionError("seconds must not silently become an index")
print("07 explicit unit conversion preserves domain meaning")这个例子只处理简单的有限十进制值;Decimal 的乘法仍受当前上下文精度影响,不能据此宣称任意大数换算都绝对精确。生产中的计费、媒体时间轴或测量系统还要明确精度、舍入、允许范围和溢出政策。这里真正要保留的设计原则是:单位换算应当出现在可见的位置,调用者应当知道什么时候丢弃了不足一帧的部分。
八 用回归测试固定接口的边界
当一个函数宣称接受“整数”时,测试不能只覆盖 0、1、2。至少应加入只提供 __index__ 的对象、只提供 __int__ 的对象、值恰好为整数的浮点数、字符串、布尔值、非法协议返回值,以及超出业务范围的整数。下面用标准库 unittest 把这些输入分组。每个失败断言都对应明确的接口承诺,今后重构时便不会因为一次方便的 int(value) 而悄悄放宽输入范围。
这里把批次数限定为一到十。代码没有先检查对象是否有某个同名属性,再尝试调用,而是直接进入 operator.index;特殊方法应定义在类型上,协议入口才是消费端的依据。测试还确认零和负数属于范围错误,浮点数和数字文本属于类型错误,这能帮助调用方区分修正值与修正输入格式。
import operator
import unittest
class Exact:
def __index__(self):
return 3
class Convertible:
def __int__(self):
return 3
class InvalidReturn:
def __index__(self):
return 3.0
def batch_count(value):
if isinstance(value, bool):
raise TypeError("boolean count is not accepted")
result = operator.index(value)
if not 1 <= result <= 10:
raise ValueError("batch count must be from 1 to 10")
return result
class CountContractTests(unittest.TestCase):
def test_accepts_exact_integer_inputs(self):
for value in (1, 10, Exact()):
with self.subTest(value=value):
self.assertIs(type(batch_count(value)), int)
self.assertEqual(batch_count(Exact()), 3)
def test_rejects_conversion_only_inputs(self):
for value in (3.0, 3.9, "3", Convertible(), InvalidReturn()):
with self.subTest(value=value):
with self.assertRaises(TypeError):
batch_count(value)
def test_rejects_boolean_inputs(self):
for value in (True, False):
with self.assertRaises(TypeError):
batch_count(value)
def test_rejects_out_of_range_integers(self):
for value in (-1, 0, 11, 10 ** 100):
with self.assertRaises(ValueError):
batch_count(value)
if __name__ == "__main__":
unittest.main()最终的判断可以落到三个具体问题上:接口需要一个转换结果,还是需要原本就有整数语义的对象;布尔值在这个业务里是否有意义;取得整数之后,还需要哪些范围、单位和资源限制。第一个问题决定选择 int 还是 operator.index,后两个问题由业务代码负责。把这些选择写成测试,协议就会从一个陌生的双下划线方法,变成可检查、可维护的接口边界。

