Skip to content

Commit f50daa1

Browse files
committed
Error when attempt to set with an array of incompatible shape.
Closes #2469
1 parent 3dd04ce commit f50daa1

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

src/zarr/core/array.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2842,14 +2842,24 @@ def set_coordinate_selection(
28422842
try:
28432843
from numcodecs.compat import ensure_ndarray_like
28442844

2845-
value = ensure_ndarray_like(value) # TODO replace with agnostic
2845+
value_array = ensure_ndarray_like(value) # TODO replace with agnostic
28462846
except TypeError:
28472847
# Handle types like `list` or `tuple`
2848-
value = np.array(value) # TODO replace with agnostic
2848+
value_array = np.array(value) # TODO replace with agnostic
28492849
if hasattr(value, "shape") and len(value.shape) > 1:
2850-
value = np.array(value).reshape(-1)
2850+
value_array = np.array(value).reshape(-1)
28512851

2852-
sync(self._async_array._set_selection(indexer, value, fields=fields, prototype=prototype))
2852+
if indexer.sel_shape != value_array.shape:
2853+
raise ValueError(
2854+
f"Attempting to set a selection of {indexer.sel_shape[0]} "
2855+
f"elements with an array of {value_array.shape[0]} elements."
2856+
)
2857+
2858+
sync(
2859+
self._async_array._set_selection(
2860+
indexer, value_array, fields=fields, prototype=prototype
2861+
)
2862+
)
28532863

28542864
@_deprecate_positional_args
28552865
def get_block_selection(

tests/test_indexing.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1936,3 +1936,21 @@ def test_zero_sized_chunks(store: StorePath, shape: list[int]) -> None:
19361936
z = Array.create(store=store, shape=shape, chunk_shape=shape, zarr_format=3, dtype="f8")
19371937
z[...] = 42
19381938
assert_array_equal(z[...], np.zeros(shape, dtype="f8"))
1939+
1940+
1941+
@pytest.mark.parametrize("store", ["memory"], indirect=["store"])
1942+
def test_vectorized_indexing_incompatible_shape(store) -> None:
1943+
# GH2469
1944+
shape = (4, 4)
1945+
chunks = (2, 2)
1946+
fill_value = 32767
1947+
arr = zarr.create(
1948+
shape,
1949+
store=store,
1950+
chunks=chunks,
1951+
dtype=np.int16,
1952+
fill_value=fill_value,
1953+
codecs=[zarr.codecs.BytesCodec(), zarr.codecs.BloscCodec()],
1954+
)
1955+
with pytest.raises(ValueError, match="Attempting to set"):
1956+
arr[np.array([1, 2]), np.array([1, 2])] = np.array([[-1, -2], [-3, -4]])

0 commit comments

Comments
 (0)