Skip to content

can't index string- and unicode- numpy-scalars with an empty tuple #7267

Description

@ahaldane

As discovered in #7259 and #7260, string- and unicode- numpy scalars do not support indexing with an empty tuple, unlike other scalars:

>>> numpy.string_("ABC")[()]
TypeError: string indices must be integers, not tuple
>>> numpy.int32(1)[()]
1

This may be a problem because indexing with an empty tuple is a way of converting possible 0-d arrays to scalars:

>>> a = numpy.int64(1)
>>> b = numpy.array(a)
>>> type(a[()]), type(b[()])
(numpy.int64, numpy.int64)

As of writing this it's not 100% clear to me we actually want this. It could be that instead of just writing

return possiblearr[()]

we should encourage people to write something like

if isinstance(possiblearr, ndarray):
    return possiblearr[()]
return possiblearr

But, on the other hand it's probably a good idea for all scalar types to behave similarly. I made a rough outline for a fix in a comment in #7260.

Activity

  1. eric-wieser commented on Mar 6, 2017

    @eric-wieser
    Member

    Related: numpy.string_("ABC")[...] fails in the same way

  2. charris commented on Mar 6, 2017

    @charris
    Member

    OTOH,

    In [5]: numpy.string_("ABC")[1]
    Out[5]: 'B'
    
  3. eric-wieser commented on Mar 6, 2017

    @eric-wieser
    Member

    This manifests itself in np.ma.array(['ab', 'cd']).take(1) due to the patch in #7586

  4. eric-wieser commented on Jul 3, 2017

    @eric-wieser
    Member

    Arguably not a bug - we're never going to have this work on object scalars, so having it fail on string scalars too forces the library writer to use a solution that works for object scalars too.

  5. InessaPawson commented on Sep 18, 2026

    @InessaPawson
    Member

    Closing this older issue in favor of #31435 for the discussion and implementation to stay in one place.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions