Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 0b97e78

Browse filesBrowse 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
Copy full SHA for 0b97e78

File tree

3 files changed

+8
-10
lines changed
Filter options

3 files changed

+8
-10
lines changed

‎changes/3027.misc.rst

Copy file name to clipboard
+1Lines 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

Copy file name to clipboardExpand all lines: src/zarr/core/buffer/core.py
+1-10Lines 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

Copy file name to clipboardExpand all lines: tests/test_buffer.py
+6Lines 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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.