Skip to content

TYP: fix str_.__getitem__ and bytes_.__getitem__ - #31879

Merged
charris merged 1 commit into
numpy:mainfrom
jorenham:typing/str_-bytes_.__getitem__
Jul 6, 2026
Merged

TYP: fix str_.__getitem__ and bytes_.__getitem__#31879
charris merged 1 commit into
numpy:mainfrom
jorenham:typing/str_-bytes_.__getitem__

Conversation

@jorenham

@jorenham jorenham commented Jul 6, 2026

Copy link
Copy Markdown
Member

At runtme the __getitem__ methods of str_ and bytes_ is inherited from builtins.str and builtins.bytes respectively. But because the stubs declare __getitem__ on generic itself (for good reasons) and the multi-inheritance order, these __getitem__ are shadowed by generic (stubs-only).

In [1]: np.str_("spam")[0]
Out[1]: 's'

In [2]: np.str_("spam")[0:]
Out[2]: 'spam'

In [3]: np.bytes_(b"spam")[0]
Out[3]: 115

In [4]: np.bytes_(b"spam")[0:]
Out[4]: b'spam'

In [5]: np.str_("spam")[()]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[5], line 1
----> 1 np.str_("spam")[()]

TypeError: string indices must be integers, not 'tuple'

In [6]: np.bytes_(b"spam")[()]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[6], line 1
----> 1 np.bytes_(b"spam")[()]

TypeError: byte indices must be integers or slices, not tuple

The fix is to override these __getitem__ methods on str_ and bytes_ using the __getitem__ typeshed signatures of str and bytes.


Fully written by me (a human, I think); bug found by Claude Fable 5 (high) (here's the full audit for those interested).

@jorenham jorenham added 09 - Backport-Candidate PRs tagged should be backported 41 - Static typing labels Jul 6, 2026
@charris
charris merged commit a209708 into numpy:main Jul 6, 2026
14 checks passed
@charris

charris commented Jul 6, 2026

Copy link
Copy Markdown
Member

Thanks Joren.

@jorenham
jorenham deleted the typing/str_-bytes_.__getitem__ branch July 6, 2026 17:09
@charris charris removed the 09 - Backport-Candidate PRs tagged should be backported label Jul 6, 2026
charris pushed a commit that referenced this pull request Jul 6, 2026
MaanasArora pushed a commit to MaanasArora/numpy that referenced this pull request Jul 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants