Skip to content

[mypyc] Support __index__ in native classes - #22100

Open
rheard wants to merge 1 commit into
python:masterfrom
rheard:index-support
Open

rheard wants to merge 1 commit into
python:masterfrom
rheard:index-support

Conversation

@rheard

@rheard rheard commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Native classes could define __index__, but it wasn't connected to the nb_index slot, so it only worked when called directly. Everything that goes through the slot raised TypeError, including operator.index(), range(), list and str indexing, slicing, hex(), sequence repetition, and the int() fallback for classes without __int__:

class C:
    def __index__(self) -> int:
        return 2

[10, 20, 30][C()]  # TypeError: list indices must be integers or slices, not C

This adds __index__ to the number slots next to __int__ and __float__, and removes it from the list of unsupported dunders in the docs.

Compiled for i in range(c) loops still failed for a different reason, which also affects objects that aren't native. That's fixed separately in #22101 .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant