Skip to content

Commit 0b97e78

Browse files
authored
simplify NDBuffer.as_scalar (#3027)
* index with an empty tuple to get scalar * changelog * add as_scalar test
1 parent 36a1bac commit 0b97e78

File tree

3 files changed

+8
-10
lines changed

3 files changed

+8
-10
lines changed

changes/3027.misc.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Simplified scalar indexing of size-1 arrays.

src/zarr/core/buffer/core.py

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -427,16 +427,7 @@ def as_scalar(self) -> ScalarType:
427427
"""Returns the buffer as a scalar value"""
428428
if self._data.size != 1:
429429
raise ValueError("Buffer does not contain a single scalar value")
430-
item = self.as_numpy_array().item()
431-
scalar: ScalarType
432-
433-
if np.issubdtype(self.dtype, np.datetime64):
434-
unit: str = np.datetime_data(self.dtype)[0] # Extract the unit (e.g., 'Y', 'D', etc.)
435-
scalar = np.datetime64(item, unit)
436-
else:
437-
scalar = self.dtype.type(item) # Regular conversion for non-datetime types
438-
439-
return scalar
430+
return cast(ScalarType, self.as_numpy_array()[()])
440431

441432
@property
442433
def dtype(self) -> np.dtype[Any]:

tests/test_buffer.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,3 +155,9 @@ def test_numpy_buffer_prototype() -> None:
155155
assert isinstance(ndbuffer.as_ndarray_like(), np.ndarray)
156156
with pytest.raises(ValueError, match="Buffer does not contain a single scalar value"):
157157
ndbuffer.as_scalar()
158+
159+
160+
# TODO: the same test for other buffer classes
161+
def test_cpu_buffer_as_scalar() -> None:
162+
buf = cpu.buffer_prototype.nd_buffer.create(shape=(), dtype="int64")
163+
assert buf.as_scalar() == buf.as_ndarray_like()[()] # type: ignore[index]

0 commit comments

Comments
 (0)