Skip to content

BUG: support () indexing for string scalars - #31448

Closed
AriGood wants to merge 1 commit into
numpy:mainfrom
AriGood:fix-str-bytes-empty-tuple
Closed

AriGood wants to merge 1 commit into
numpy:mainfrom
AriGood:fix-str-bytes-empty-tuple

Conversation

@AriGood

@AriGood AriGood commented May 16, 2026 •

Copy link
Copy Markdown

PR summary

Zero-dimensional arrays and NumPy scalar types are documented to support the empty-tuple index x[()] as a scalar index that returns the scalar value. However, np.str_ and np.bytes_ scalars currently raise TypeError when indexed with scalar[()], because the index is handled by the underlying Python str/bytes mapping implementation instead of NumPy’s scalar indexing behavior.

This change makes np.str_ and np.bytes_ scalars treat scalar[()] as a scalar index and return the scalar value, consistent with other 0‑d NumPy scalars. All other indices are still delegated to the Python str/bytes mapping implementation to preserve existing behavior.

In addition, it adds regression tests in
numpy/_core/tests/test_scalarmath.py that assert:

  • np.str_("abc").shape == () and np.str_("abc")[()] returns the same
    scalar value.
  • np.bytes_(b"abc").shape == () and np.bytes_(b"abc")[()] returns
    the same scalar value.

Fixes gh-31435.

First time committer introduction

Hi, this is my first contribution to NumPy. I use NumPy a lot in my own projects, so I wanted to help improve a library I use a lot and start getting involved in open source development.

AI Disclosure

ChatGPT was used to help make sure this PR is following guidelines. No AI code was used.

Copilot AI review requested due to automatic review settings May 16, 2026 19:51
@jorenham
jorenham removed the request for review from Copilot May 16, 2026 20:27
@seberg

seberg commented May 17, 2026

Copy link
Copy Markdown
Member

Thanks, but I'll close this until the discussion on the issue is even somewhat close to a decision that this makes sense.

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.

BUG: numpy.str_ and numpy.bytes_ scalars do not support [()] indexing despite having shape == ()

2 participants