Skip to content

simplify NDBuffer.as_scalar #3027

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/3027.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Simplified scalar indexing of size-1 arrays.
11 changes: 1 addition & 10 deletions src/zarr/core/buffer/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,16 +427,7 @@
"""Returns the buffer as a scalar value"""
if self._data.size != 1:
raise ValueError("Buffer does not contain a single scalar value")
item = self.as_numpy_array().item()
scalar: ScalarType

if np.issubdtype(self.dtype, np.datetime64):
unit: str = np.datetime_data(self.dtype)[0] # Extract the unit (e.g., 'Y', 'D', etc.)
scalar = np.datetime64(item, unit)
else:
scalar = self.dtype.type(item) # Regular conversion for non-datetime types

return scalar
return cast(ScalarType, self.as_numpy_array()[()])

Check warning on line 430 in src/zarr/core/buffer/core.py

View check run for this annotation

Codecov / codecov/patch

src/zarr/core/buffer/core.py#L430

Added line #L430 was not covered by tests

@property
def dtype(self) -> np.dtype[Any]:
Expand Down
6 changes: 6 additions & 0 deletions tests/test_buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,9 @@ def test_numpy_buffer_prototype() -> None:
assert isinstance(ndbuffer.as_ndarray_like(), np.ndarray)
with pytest.raises(ValueError, match="Buffer does not contain a single scalar value"):
ndbuffer.as_scalar()


# TODO: the same test for other buffer classes
def test_cpu_buffer_as_scalar() -> None:
buf = cpu.buffer_prototype.nd_buffer.create(shape=(), dtype="int64")
assert buf.as_scalar() == buf.as_ndarray_like()[()] # type: ignore[index]