Skip to content

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

Open

Description

@Robertboy18

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

Activity

  1. added
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    type-bugAn unexpected behavior, bug, or error
    on Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions