Skip to content

Commit 58ff3ec

Browse files
authored
Error when attempting to set with an array of incompatible shape. (#2512)
* Error when attempt to set with an array of incompatible shape. Closes #2469 * Fix typing * fix isinstance check
1 parent 501ae9e commit 58ff3ec

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/zarr/core/array.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2881,6 +2881,14 @@ def set_coordinate_selection(
28812881
if hasattr(value, "shape") and len(value.shape) > 1:
28822882
value = np.array(value).reshape(-1)
28832883

2884+
if not is_scalar(value, self.dtype) and (
2885+
isinstance(value, NDArrayLike) and indexer.shape != value.shape
2886+
):
2887+
raise ValueError(
2888+
f"Attempting to set a selection of {indexer.sel_shape[0]} "
2889+
f"elements with an array of {value.shape[0]} elements."
2890+
)
2891+
28842892
sync(self._async_array._set_selection(indexer, value, fields=fields, prototype=prototype))
28852893

28862894
@_deprecate_positional_args

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)