Skip to content

Commit

Permalink
Merge pull request numpy#25974 from goncalobarias/dtype-negative-size…
Browse files Browse the repository at this point in the history
…d-error

BUG: Raise error for negative-sized fixed-width dtype
  • Loading branch information
ngoldbaum authored Mar 11, 2024
2 parents e7568e9 + 695733a commit 160d2c6
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
5 changes: 5 additions & 0 deletions numpy/_core/src/multiarray/descriptor.c
Original file line number Diff line number Diff line change
Expand Up @@ -1813,6 +1813,11 @@ _convert_from_str(PyObject *obj, int align)

/* Parse the integer, make sure it's the rest of the string */
elsize = (int)strtol(type + 1, &typeend, 10);
/* Make sure size is not negative */
if (elsize < 0) {
goto fail;
}

if (typeend - type == len) {

kind = type[0];
Expand Down
5 changes: 5 additions & 0 deletions numpy/_core/tests/test_dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ def test_invalid_types(self):
assert_raises(TypeError, np.dtype, 'q8')
assert_raises(TypeError, np.dtype, 'Q8')

# Make sure negative-sized dtype raises an error
assert_raises(TypeError, np.dtype, 'S-1')
assert_raises(TypeError, np.dtype, 'U-1')
assert_raises(TypeError, np.dtype, 'V-1')

def test_richcompare_invalid_dtype_equality(self):
# Make sure objects that cannot be converted to valid
# dtypes results in False/True when compared to valid dtypes.
Expand Down
3 changes: 1 addition & 2 deletions numpy/_core/tests/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

import numpy as np
from numpy._core import umath, sctypes
from numpy._core._exceptions import _ArrayMemoryError
from numpy._core.numerictypes import obj2sctype
from numpy._core.arrayprint import set_string_function
from numpy.exceptions import AxisError
Expand Down Expand Up @@ -3345,7 +3344,7 @@ class MyNDArray(np.ndarray):
assert_(type(b) is not MyNDArray)

# Test invalid dtype
with assert_raises(_ArrayMemoryError):
with assert_raises(TypeError):
a = np.array(b"abc")
like_function(a, dtype="S-1", **fill_kwarg)

Expand Down

0 comments on commit 160d2c6

Please sign in to comment.