Skip to content

Commit 203812f

Browse files
authored
fix: better error message for mismatched views (#794)
* fix: better error message for mismatched views Signed-off-by: Henry Schreiner <[email protected]> * fix: slightly nicer still err output Signed-off-by: Henry Schreiner <[email protected]> Signed-off-by: Henry Schreiner <[email protected]>
1 parent 4ebce75 commit 203812f

File tree

1 file changed

+14
-8
lines changed
  • src/boost_histogram/_internal

1 file changed

+14
-8
lines changed

src/boost_histogram/_internal/view.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,16 +39,22 @@ def __setitem__(self, ind: StrIndex, value: ArrayLike) -> None:
3939
super().__setitem__(ind, value) # type: ignore[no-untyped-call]
4040
return
4141

42+
current_ndim = super().__getitem__(ind).ndim
43+
4244
array: "np.typing.NDArray[Any]" = np.asarray(value)
43-
if (
44-
array.ndim == super().__getitem__(ind).ndim + 1
45-
and len(self._FIELDS) == array.shape[-1]
46-
):
47-
self.__setitem__(ind, self._PARENT._array(*np.moveaxis(array, -1, 0))) # type: ignore[attr-defined]
48-
elif self.dtype == array.dtype:
45+
msg = "Needs matching ndarray or n+1 dim array"
46+
if array.ndim == current_ndim + 1:
47+
if len(self._FIELDS) == array.shape[-1]:
48+
self.__setitem__(ind, self._PARENT._array(*np.moveaxis(array, -1, 0))) # type: ignore[attr-defined]
49+
return
50+
msg += f", final dimension should be {len(self._FIELDS)} for this storage, got {array.shape[-1]} instead"
51+
raise ValueError(msg)
52+
if self.dtype == array.dtype:
4953
super().__setitem__(ind, array) # type: ignore[no-untyped-call]
50-
else:
51-
raise ValueError("Needs matching ndarray or n+1 dim array")
54+
return
55+
56+
msg += f", {current_ndim}D {self.dtype} or {current_ndim+1}D required, got {array.ndim}D {array.dtype}"
57+
raise ValueError(msg)
5258

5359

5460
def make_getitem_property(name: str) -> property:

0 commit comments

Comments
 (0)