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

オープン 初心者向け
#162,466 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
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) で変換しています。まずこの2つの関数と、sq_ass_item をすでに確認している非インデックス側の分岐を読んでください。tuple、set、str、range に巨大な int を使って要素の代入または削除を行うと TypeError が発生するようになり、報告にある4つのケースを対象とした 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分
マージ済み PR(30日)
610

環境構築

Codespaces で開く

このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

python/cpython のほかの issue

python/cpython の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。