Item assignment and deletion raise `IndexError` instead of `TypeError` on types without them, for a huge index

未关闭 适合新手
#162,466 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
62/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
c, python
领域
backend

调研方向

缺陷位于 Objects/abstract.c 中的 PyObject_SetItem 和 PyObject_DelItem。这里在检查 sq_ass_item 是否存在之前,先用 PyNumber_AsSsize_t(key, PyExc_IndexError) 转换索引键。请先阅读这两个函数,以及已经检查 sq_ass_item 的非索引分支。当 tuple、set、str 和 range 使用超大 int 进行元素赋值或删除时抛出 TypeError,并且 Lib/test 中覆盖报告中四种情况的回归测试通过,即为完成。

由索引模型根据 Issue 内容生成。

描述

interpreter-core type-bug

Bug report

Bug description:

Assigning to or deleting an item of a tuple, str, bytes, range, set or frozenset raises TypeError, unless the index is an int that doesn't fit in a Py_ssize_t. Then it raises IndexError, although the type supports no item assignment or deletion at all:

for stmt in ["s = {1}; s[0] = 0", "s = {1}; s[2**63] = 0", "t = (1, 2); del t[0]", "t = (1, 2); del t[2**63]"]:
    try:
        exec(stmt)
    except Exception as e:
        print(f"{stmt:26} {type(e).__name__}: {e}")
s = {1}; s[0] = 0          TypeError: 'set' object does not support item assignment
s = {1}; s[2**63] = 0      IndexError: cannot fit 'int' into an index-sized integer
t = (1, 2); del t[0]       TypeError: 'tuple' object doesn't support item deletion
t = (1, 2); del t[2**63]   IndexError: cannot fit 'int' into an index-sized integer

A set isn't even subscriptable, and s[2**63] (a read) does give TypeError: 'set' object is not subscriptable. The cause is in PyObject_SetItem and PyObject_DelItem (Objects/abstract.c): when the type has tp_as_sequence, an index key is converted with PyNumber_AsSsize_t(key, PyExc_IndexError) before anyone checks that sq_ass_item exists. The branch for a non-index key already checks sq_ass_item; checking it first in both branches would give the TypeError. PyPy 3.12 raises TypeError in all four cases. I found it while writing a Lean spec of Python.

CPython versions tested on:

3.12, 3.15, CPython main branch

Operating systems tested on:

Linux

主要语言
Python
星标
78.4k
派生
36.6k
平均合并
23 小时 34 分钟
30 天内合并 PR
610

环境准备

在 Codespaces 中打开

在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

python/cpython 的其他 Issue

查看 python/cpython 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。