Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
Back to tool/Back to issues
#27301·numpy

BUG: Corner cases for zero-length string dtypes - array copying changes dtype

Author: mhvkCreated Aug 28, 2024Updated Sep 30, 2026
Labels00 - BugProjectcomponent: numpy.dtype

Describe the issue:

While trying to debug a corner case in which zero length strings are used (https://github.com/astropy/astropy/pull/16894), we realized that the following does not work generically for a given array a with non-zero length:

np.dtype((a.dtype, a.shape[1:]))

In particular, if one has an array that has only zero-length strings in it. This boils down to the following not working:

np.dtype(("S", ()))

Here, any shape tuple will fail, though one can pass in 0.

Reproduce the code example:

python
import numpy as np
np.dtype(("S", ()))

Error message:

bash
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[5], line 1
----> 1 np.dtype(("S", ()))

ValueError: invalid itemsize in generic type tuple

Python and NumPy Versions:

2.1.0 3.11.2 (main, May 2 2024, 11:59:08) [GCC 12.2.0]

Runtime Environment:

No response

Context for the issue:

EDIT: Another strange thing is that zero-length string dtypes are not properly preserved:

data = np.array([("", 12)], dtype=[("a", "U"), ("b", "i4")])
np.array(data["a"], copy=False)
# array([''], dtype='<U0')
np.array(data["a"], copy=True)
# array([''], dtype='<U1')

This is not OK, obviously (Note that in fact I do not quite know how to create a zero-width string array without using a structured dtype; they are really used, so do not remove this option!!).

p.s. Also data["a"].copy() creates a length-1 string array.

Source: numpy/numpy

View original on GitHubView discussion on GitHub