Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions include/pybind11/numpy.h
Original file line number Diff line number Diff line change
Expand Up @@ -1158,7 +1158,7 @@ class array : public buffer {

/// Dimension along a given axis
ssize_t shape(ssize_t dim) const {
if (dim >= ndim()) {
if (dim < 0 || dim >= ndim()) {
fail_dim_check(dim, "invalid axis");
}
return shape()[dim];
Expand All @@ -1176,7 +1176,7 @@ class array : public buffer {

/// Stride along a given axis
ssize_t strides(ssize_t dim) const {
if (dim >= ndim()) {
if (dim < 0 || dim >= ndim()) {
fail_dim_check(dim, "invalid axis");
}
return strides()[dim];
Expand Down Expand Up @@ -1356,7 +1356,7 @@ class array : public buffer {

template <typename... Ix>
void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const {
if (i >= *shape) {
if (i < 0 || i >= *shape) {
throw index_error(std::string("index ") + std::to_string(i)
+ " is out of bounds for axis " + std::to_string(axis)
+ " with size " + std::to_string(*shape));
Expand Down
14 changes: 14 additions & 0 deletions tests/test_numpy_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ def test_array_attributes():
with pytest.raises(IndexError) as excinfo:
m.strides(a, 2)
assert str(excinfo.value) == "invalid axis: 2 (ndim = 2)"
with pytest.raises(IndexError) as excinfo:
m.shape(a, -1)
assert str(excinfo.value) == "invalid axis: -1 (ndim = 2)"
with pytest.raises(IndexError) as excinfo:
m.strides(a, -1)
assert str(excinfo.value) == "invalid axis: -1 (ndim = 2)"
assert not m.writeable(a)
assert m.size(a) == 6
assert m.itemsize(a) == 2
Expand Down Expand Up @@ -217,6 +223,14 @@ def test_bounds_check(arr):
with pytest.raises(IndexError) as excinfo:
func(arr, 0, 4)
assert str(excinfo.value) == "index 4 is out of bounds for axis 1 with size 3"
# Negative indices are out of bounds too (they would address memory
# before the start of the buffer).
with pytest.raises(IndexError) as excinfo:
func(arr, -1, 0)
assert str(excinfo.value) == "index -1 is out of bounds for axis 0 with size 2"
with pytest.raises(IndexError) as excinfo:
func(arr, 0, -1)
assert str(excinfo.value) == "index -1 is out of bounds for axis 1 with size 3"


def test_make_c_f_array():
Expand Down
Loading