Python slice.indices 实战:负步长边界为什么不能直接回填切片

10-22 5阅读

需要记录“这次切片到底选中了原序列的哪些位置”时,手写负数换算和越界裁剪很容易漏掉边界。Python 内置的 slice.indices(length) 可以把切片转换成适合交给 range 的三元组。最重要的用法是 range(*s.indices(len(seq)));把这个三元组重新塞回方括号切片,则可能改变结果。

本文在 CPython 3.12.14 上实际执行全部示例,普通模式和 -O 模式结果一致。一手资料核验日期为 2026 年 10 月 22 日(北京时间)。官方 /3.12 文档目前显示 3.12.15,因此文档用于说明接口,细节同时对照固定 v3.12.14 源码和本次运行结果,不把滚动文档标成 3.12.14 的实测版本。

Python slice.indices 实战:负步长边界为什么不能直接回填切片

配图为独立模型生成的概念示意图,不是 Python 调试器截图;左侧 -1 表示本例逆向遍历的排除边界,不表示要读取 seq[-1]。

一、先看能运行的最小工具

保存为 slice_lab.py。normalize 负责调用内置归一化;positions 返回 range,不先生成位置列表;gather 则逐位置取值,并明确返回 list。这里只讨论长度稳定、遵循普通整数位置索引的序列,例如没有在读取途中被修改的 list、tuple 和 str。

"""Use the built-in slice rules instead of reimplementing their boundaries."""
def normalize(length, spec):
    return spec.indices(length)


def positions(length, spec):
    return range(*normalize(length, spec))


def gather(seq, spec):
    # Requires stable length and ordinary integer-index sequence semantics.
    return [seq[i] for i in positions(len(seq), spec)]


def main():
    seq = "abcdef"
    spec = slice(None, None, -1)
    bounds = normalize(len(seq), spec)
    print("normalized:", bounds)
    print("positions:", list(positions(len(seq), spec)))
    print("gathered:", gather(seq, spec))
    print("re-sliced:", repr(seq[slice(*bounds)]))
    print("explicit -1 stop:", list(positions(6, slice(None, -1, -1))))


if __name__ == "__main__":
    main()

运行 python3 slice_lab.py,预期输出如下。引号用于让空字符串清晰可见。

normalized: (5, -1, -1)
positions: [5, 4, 3, 2, 1, 0]
gathered: ['f', 'e', 'd', 'c', 'b', 'a']
re-sliced: ''
explicit -1 stop: []

原始切片选中了 f 到 a,但把归一化结果重新构造成切片后,字符串却变成空串。这个差别值得单独理解。

二、负步长的 -1 为什么不能直接回填

对长度为 6 的序列,slice(None, None, -1).indices(6) 得到 (5, -1, -1)。交给 range 后,从 5 开始,每次减 1,在到达 -1 之前结束,所以最后一个位置是 0。此处 stop=-1 是供整数遍历使用的排除边界。

而 seq[5:-1:-1] 中的 -1 是一个重新输入的显式负索引,仍要按“长度加负索引”的规则处理。它被换算成 5,于是等价于从 5 向后走、却要求停在不包含的 5,结果为空。原始 stop=None 与原始 stop=-1 不相同:

  • slice(None, None, -1):省略 stop,完整逆序,位置是 5、4、3、2、1、0。

  • slice(None, -1, -1):显式 stop=-1,归一化 stop 为 5,结果为空。

  • slice(None, 0, -1):显式 stop=0,位置是 5、4、3、2、1,不包含 0。

因此需要保留切片语义时,保留原始 slice 对象;需要遍历选中位置时,使用归一化结果构造 range。不要把归一化三元组当成可以无条件再次切片的序列化格式。官方 slice.indices 接口说明定义了按给定长度处理缺省值和越界值的行为;固定版本 v3.12.14 的 sliceobject.c也区分 None 分支与显式负边界分支。

三、归一化处理的是边界,不保证每个数字都是有效下标

设长度 n 不小于 0。步长为正时,缺省 start 为 0、stop 为 n,边界裁剪到 0 至 n;步长为负时,缺省 start 为 n-1、stop 为 -1,边界裁剪到 -1 至 n-1。显式负边界先加 n,再进行相应裁剪。stop 始终不被选中。

例如长度为 6 时,slice(-100, 100, 2) 归一化为 (0, 6, 2),选中 0、2、4;slice(100, -100, -2) 归一化为 (5, -1, -2),选中 5、3、1。切片越界通常被裁剪,和直接读取 seq[100] 的行为不同。完整规则见 官方通用序列操作说明。

n=0 时,逆向完整切片得到 (-1, -1, -1),但 range 没有任何元素。这说明不能看到返回值里有 -1,就直接读取 seq[-1];正向空切片的 start 也可能等于 n。真正需要访问的位置由整个 range 决定。归一化不会改写原 slice 的 start、stop、step 属性。

四、整数协议比 int 转换更严格

创建 slice 对象时可以暂存任意类型的属性,错误不一定立即发生。调用 indices 或把它用于普通序列切片时,才会验证相关参数。步长省略或为 None 时取 1;步长为 0 会抛出 ValueError,长度为负同样会抛出 ValueError。

长度以及非 None 的起点、终点、步长需要支持整数索引协议。实现 __index__ 且返回整数的对象可以使用;只有 __int__ 不够。6.0 虽然数值上没有小数部分,也不能作为这里的长度;"6" 同样不行。不要先调用 int 清洗输入,否则小数会被截断、数字字符串会被接受,接口的约束已经发生变化。协议说明见 __index__ 数据模型,需要单独执行同类转换时可用 operator.index。

bool 是一个需要主动认识的边界:Python 将它视为整数子类型,True 可作 1,False 可作 0。因此 False 作为步长会触发零步长错误,而 True 作为长度可以接受。如果业务 API 不允许布尔参数,应明确添加业务校验,不要把这种限制误称为 Python 自带规则。

本次还检查了超大整数边界,以及长度 10**100、切片只选前三项的归一化。它们不会要求创建一个那样长的真实序列。不要据此推断 len(真实对象)、把巨大 range 转成 list 或其他序列 API 都没有尺寸限制;本文没有测试这些额外能力。

五、先写独立预期,再运行 36 项检查

下面三个文件与 slice_lab.py 放在同一目录,无第三方依赖,也不需要下载隐藏测试数据。oracle.py 的期望三元组、位置列表、异常类型和输出文本在实现及测试运行器之前手工固定;没有用被测 normalize 或 slice.indices 动态生成期望值。

检查由 22 个合法输入、12 个非法输入和 2 个行为检查构成。合法输入同时核对归一化三元组与位置列表;非法输入核对异常类型,不依赖可能变化的异常文案。最后两项覆盖再次切片陷阱及原始 slice 属性保持不变。检查使用显式 require,不依赖在 -O 下会被移除的 assert。

文件 oracle.py

"""Hand-written expected values; fixed before the implementation was written."""
class Index:
    def __init__(self, value):
        self.value = value

    def __index__(self):
        return self.value


class IntOnly:
    def __int__(self):
        return 2


class BadIndex:
    def __index__(self):
        return 2.0


# name, length, (start, stop, step), normalized triple, selected positions
VALID = [
    ("all", 6, (None, None, None), (0, 6, 1), [0, 1, 2, 3, 4, 5]),
    ("stride", 6, (1, 5, 2), (1, 5, 2), [1, 3]),
    ("reverse", 6, (None, None, -1), (5, -1, -1), [5, 4, 3, 2, 1, 0]),
    ("reverse_stride", 6, (4, 0, -2), (4, 0, -2), [4, 2]),
    ("explicit_minus_one_stop", 6, (None, -1, -1), (5, 5, -1), []),
    ("explicit_minus_one_start", 6, (-1, None, -1), (5, -1, -1), [5, 4, 3, 2, 1, 0]),
    ("forward_clamp", 6, (-100, 100, 2), (0, 6, 2), [0, 2, 4]),
    ("reverse_clamp", 6, (100, -100, -2), (5, -1, -2), [5, 3, 1]),
    ("start_too_high", 6, (100, None, None), (6, 6, 1), []),
    ("reverse_start_too_low", 6, (-100, None, -1), (-1, -1, -1), []),
    ("forward_empty", 6, (4, 1, 1), (4, 1, 1), []),
    ("reverse_empty", 6, (1, 4, -1), (1, 4, -1), []),
    ("empty_forward", 0, (None, None, None), (0, 0, 1), []),
    ("empty_reverse", 0, (None, None, -1), (-1, -1, -1), []),
    ("negative_bounds", 6, (-4, -1, 1), (2, 5, 1), [2, 3, 4]),
    ("stop_before_first", 6, (None, -7, -1), (5, -1, -1), [5, 4, 3, 2, 1, 0]),
    ("stop_at_zero", 6, (None, 0, -1), (5, 0, -1), [5, 4, 3, 2, 1]),
    ("default_step", 6, (1, 4, None), (1, 4, 1), [1, 2, 3]),
    ("huge_bounds", 6, (-10**100, 10**100, 2), (0, 6, 2), [0, 2, 4]),
    ("index_protocol", Index(6), (Index(1), Index(5), Index(2)), (1, 5, 2), [1, 3]),
    ("bool_is_integer", True, (False, True, True), (0, 1, 1), [0]),
    ("huge_length", 10**100, (0, 3, None), (0, 3, 1), [0, 1, 2]),
]

# name, length, raw slice fields, expected exception type
INVALID = [
    ("zero_step", 6, (None, None, 0), ValueError),
    ("false_step", 6, (None, None, False), ValueError),
    ("negative_length", -1, (None, None, None), ValueError),
    ("float_length", 6.0, (None, None, None), TypeError),
    ("string_length", "6", (None, None, None), TypeError),
    ("float_start", 6, (1.0, None, None), TypeError),
    ("string_stop", 6, (None, "5", None), TypeError),
    ("float_step", 6, (None, None, 2.0), TypeError),
    ("int_only_start", 6, (IntOnly(), None, None), TypeError),
    ("int_only_length", IntOnly(), (None, None, None), TypeError),
    ("bad_index_stop", 6, (None, BadIndex(), None), TypeError),
    ("bad_index_length", BadIndex(), (None, None, None), TypeError),
]

EXPECTED_DEMO = """normalized: (5, -1, -1)
positions: [5, 4, 3, 2, 1, 0]
gathered: ['f', 'e', 'd', 'c', 'b', 'a']
re-sliced: ''
explicit -1 stop: []
"""
EXPECTED_TEST_OUTPUT = "PASS: 36 checks\n"
EXPECTED_MUTATION_OUTPUT = "PASS: 10 semantic mutants rejected; 10 witnesses returned normally\n"

文件 test_slice_lab.py

from oracle import VALID, INVALID
from slice_lab import normalize, gather


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


def evaluate(candidate):
    failures = []
    for name, length, fields, expected_bounds, expected_positions in VALID:
        try:
            bounds = candidate(length, slice(*fields))
            actual = list(range(*bounds))
            require(bounds == expected_bounds, f"{name}: wrong bounds {bounds!r}")
            require(actual == expected_positions, f"{name}: wrong positions {actual!r}")
        except Exception as exc:
            failures.append(f"{name}: {type(exc).__name__}: {exc}")
    for name, length, fields, expected_error in INVALID:
        try:
            candidate(length, slice(*fields))
        except Exception as exc:
            if type(exc) is not expected_error:
                failures.append(f"{name}: wrong exception {type(exc).__name__}")
        else:
            failures.append(f"{name}: expected {expected_error.__name__}")
    return failures


def main():
    failures = evaluate(normalize)
    require(not failures, "\n".join(failures))
    # Behavioral check 35: an independent literal catches the re-slicing trap.
    seq = "abcdef"
    spec = slice(None, None, -1)
    require(gather(seq, spec) == ['f', 'e', 'd', 'c', 'b', 'a']
            and seq[slice(*normalize(6, spec))] == "", "sentinel trap")
    # Behavioral check 36: normalization does not rewrite the original slice.
    raw = slice(-20, 20, 2)
    normalize(6, raw)
    require((raw.start, raw.stop, raw.step) == (-20, 20, 2), "slice mutated")
    require(len(VALID) + len(INVALID) + 2 == 36, "case count")
    print("PASS: 36 checks")


if __name__ == "__main__":
    main()

六、用十种会正常返回的错误实现检验测试

只看到绿色结果,还不知道测试能否抓住常见误写。下面故意制造十种语义错误:把 stop 算进去、强制正步长、丢掉步幅、二次归一化、把省略 stop 当成 -1、负向边界错误裁到 0、正向边界错误裁到最后一个元素、用 int 放宽边界、用 int 放宽长度,以及把零步长当成 1。

每个变异先执行一个见证输入,要求函数和随后 range 的求值都正常完成,再检查它是否违反预先固定的预期,以及同一测试器能否抓到该项错误。语法错误、导入失败和见证输入崩溃不算“发现语义错误”。变异运行的是前面的 34 个归一化输入用例;额外两项行为检查属于原实现的 36 项回归检查,没有拿它们增加变异计数。

文件 mutation_checks.py

from operator import index
from oracle import VALID, INVALID
from test_slice_lab import evaluate, require


def shifted_stop(n, s):
    a, b, c = s.indices(n)
    return a, b + (1 if c > 0 else -1), c


def positive_step(n, s):
    a, b, c = s.indices(n)
    return a, b, abs(c)


def unit_step(n, s):
    a, b, c = s.indices(n)
    return a, b, 1 if c > 0 else -1


def normalize_twice(n, s):
    return slice(*s.indices(n)).indices(n)


def omitted_stop_is_minus_one(n, s):
    return slice(s.start, -1 if s.stop is None else s.stop, s.step).indices(n)


def negative_floor_zero(n, s):
    a, b, c = s.indices(n)
    return (max(0, a), max(0, b), c) if c < 0 else (a, b, c)


def positive_cap_last(n, s):
    a, b, c = s.indices(n)
    last = index(n) - 1
    return (min(a, last), min(b, last), c) if c > 0 else (a, b, c)


def coerce_bounds(n, s):
    fields = [None if v is None else int(v) for v in (s.start, s.stop, s.step)]
    return slice(*fields).indices(n)


def coerce_length(n, s):
    return s.indices(int(n))


def zero_means_one(n, s):
    return slice(s.start, s.stop, 1 if s.step == 0 else s.step).indices(n)


# Every witness must return normally, yet disagree with the fixed contract.
MUTANTS = [
    (shifted_stop, "stride"),
    (positive_step, "reverse"),
    (unit_step, "stride"),
    (normalize_twice, "reverse"),
    (omitted_stop_is_minus_one, "reverse"),
    (negative_floor_zero, "reverse"),
    (positive_cap_last, "all"),
    (coerce_bounds, "float_start"),
    (coerce_length, "float_length"),
    (zero_means_one, "zero_step"),
]


def main():
    valid = {row[0]: row for row in VALID}
    invalid = {row[0]: row for row in INVALID}
    for mutant, witness in MUTANTS:
        row = valid.get(witness, invalid.get(witness))
        _, length, fields, *expected = row
        actual = mutant(length, slice(*fields))
        # A crash here is not counted as rejection of a semantic mutant.
        list(range(*actual))
        if witness in valid:
            require(actual != expected[0], f"{mutant.__name__}: unchanged witness")
        failures = evaluate(mutant)
        require(any(line.startswith(witness + ":") for line in failures),
                f"{mutant.__name__}: witness escaped the checker")
    print("PASS: 10 semantic mutants rejected; 10 witnesses returned normally")


if __name__ == "__main__":
    main()

七、运行命令与实测结果

在四个文件所在目录运行以下命令。将 python3 替换为自己的 Python 3.12 解释器命令即可。文中的版本结论对应实际使用的 3.12.14,不声称已在其他版本重复执行。

python3 --version
python3 slice_lab.py
python3 test_slice_lab.py
python3 mutation_checks.py
python3 -O slice_lab.py
python3 -O test_slice_lab.py
python3 -O mutation_checks.py

版本命令输出 Python 3.12.14。两次示例程序均输出前文列出的五行结果;两种模式下的测试摘要均为:

PASS: 36 checks
PASS: 10 semantic mutants rejected; 10 witnesses returned normally

实测共执行普通模式和 -O 模式各一轮,36 项原实现检查均通过,十种语义变异均被拒绝,十个见证输入均正常返回。这里验证的是本文列出的边界契约,并非穷举所有 Python 切片行为,也没有覆盖带副作用的 __index__、读取中变化的序列长度或自定义 __getitem__ 的特殊解释。

八、放进真实代码时的取舍

只想拿切片结果,直接 seq[s] 往往最清楚,还能保留序列自己的结果类型。需要原始位置,例如生成采样日志、把选中位置映射回输入记录、实现遵循标准切片规则的自定义容器时,再使用 positions。gather 只是教学辅助,它返回 list,保留元素引用,不是深拷贝,也不提供并发修改保护。

可以记住这个操作顺序:保留原始 slice,取得当前长度,用 indices 归一化,然后交给 range。这样负索引、缺省边界和越界裁剪由 Python 处理,而 -1 哨兵不会在第二次切片时被重新解释。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。