Skip to content

Commit ce25ec3

Browse files
committed
Add as_bytes_like method to Buffer
1 parent 03bd569 commit ce25ec3

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

src/zarr/core/buffer/core.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,19 @@ def as_numpy_array(self) -> npt.NDArray[Any]:
251251
"""
252252
...
253253

254+
def as_bytes_like(self) -> BytesLike:
255+
"""Returns the buffer as a bytes-like object.
256+
257+
Notes
258+
-----
259+
Might have to copy data, since the implementation uses `.as_numpy_array()`.
260+
261+
Returns
262+
-------
263+
A bytes-like object that implements the Python buffer protocol
264+
"""
265+
return memoryview(self.as_numpy_array().view(np.uint8)) # type: ignore[arg-type]
266+
254267
def to_bytes(self) -> bytes:
255268
"""Returns the buffer as `bytes` (host memory).
256269

src/zarr/storage/_obstore.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@
77
from collections.abc import Iterable
88
from typing import TYPE_CHECKING, Any, TypedDict
99

10-
import numpy as np
11-
1210
from zarr.abc.store import (
1311
ByteRequest,
1412
OffsetByteRequest,
@@ -147,15 +145,15 @@ async def set(self, key: str, value: Buffer) -> None:
147145

148146
self._check_writable()
149147

150-
buf = value.as_numpy_array().view(np.uint8)
148+
buf = value.as_bytes_like()
151149
await obs.put_async(self.store, key, buf)
152150

153151
async def set_if_not_exists(self, key: str, value: Buffer) -> None:
154152
# docstring inherited
155153
import obstore as obs
156154

157155
self._check_writable()
158-
buf = value.as_numpy_array().view(np.uint8)
156+
buf = value.as_bytes_like()
159157
with contextlib.suppress(obs.exceptions.AlreadyExistsError):
160158
await obs.put_async(self.store, key, buf, mode="create")
161159

0 commit comments

Comments
 (0)