Skip to content
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

feature(group): add group setitem api #2393

Merged
merged 8 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
8 changes: 6 additions & 2 deletions src/zarr/api/asynchronous.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,12 +396,16 @@ async def save_array(

mode = kwargs.pop("mode", None)
store_path = await make_store_path(store, path=path, mode=mode, storage_options=storage_options)
if np.isscalar(arr):
arr = np.array(arr)
shape = arr.shape
chunks = getattr(arr, "chunks", shape) # for array-likes with chunks attribute
new = await AsyncArray.create(
store_path,
zarr_format=zarr_format,
shape=arr.shape,
shape=shape,
dtype=arr.dtype,
chunks=arr.shape,
chunks=chunks,
**kwargs,
)
await new.setitem(slice(None), arr)
Expand Down
60 changes: 55 additions & 5 deletions src/zarr/core/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,36 @@ def flatten(
return metadata


class ArraysProxy:
"""
Proxy for arrays in a group.

Used to implement the `Group.arrays` property
"""

def __init__(self, group: Group) -> None:
self._group = group

def __getitem__(self, key: str) -> Array:
obj = self._group[key]
if isinstance(obj, Array):
return obj
raise KeyError(key)

def __setitem__(self, key: str, value: npt.ArrayLike) -> None:
"""
Set an array in the group.
"""
self._group._sync(self._group._async_group.set_array(key, value))

def __iter__(self) -> Generator[tuple[str, Array], None]:
for name, async_array in self._group._sync_iter(self._group._async_group.arrays()):
yield name, Array(async_array)

def __call__(self) -> Generator[tuple[str, Array], None]:
return iter(self)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could use some opinions here!

On one hand, iter(group.arrays) is nice and tidy. But it also doesn't match the existing API (group.arrays()) and there are other methods where symetry seems useful (array_keys, array_values, etc.).

@d-v-b - you'll have an opinion here :)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what breaks if we remove __call__? I feel like that's redundant if you can just iterate. And then we could add keys and values methods to the ArraysProxy object that lossily call __iter__, thereby replacing array_keys and array_values?

We end up with a kind of a weird data structure -- something that's asymptotically a dict? But I think that also matches the semantics of "lots of stuff stored on disk with unique names".

Copy link
Member Author

@jhamman jhamman Oct 17, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what breaks if we remove call

lots of stuff that looks like this (from our test suite):

>       assert sorted(group.arrays(), key=lambda x: x[0]) == expected_arrays
E       TypeError: 'ArraysProxy' object is not callable

Looking at 2.18, I'm realizing we also are missing the recurse option to Group.arrays(recurse: bool = False)...

All of this makes me think it may be asking too much to overload .arrays with setiem/getitem/iter/etc.



@dataclass(frozen=True)
class GroupMetadata(Metadata):
attributes: dict[str, Any] = field(default_factory=dict)
Expand Down Expand Up @@ -596,6 +626,21 @@ def from_dict(
store_path=store_path,
)

async def set_array(self, key: str, value: Any) -> None:
"""fastpath for creating a new array

Parameters
----------
key : str
Array name
value : array-like
Array data
"""
path = self.store_path / key
await async_api.save_array(
store=path, arr=value, zarr_format=self.metadata.zarr_format, exists_ok=True
)

async def getitem(
self,
key: str,
Expand Down Expand Up @@ -1368,9 +1413,14 @@ def __iter__(self) -> Iterator[str]:
def __len__(self) -> int:
return self.nmembers()

@deprecated("Use Group.arrays setter instead.")
def __setitem__(self, key: str, value: Any) -> None:
"""__setitem__ is not supported in v3"""
raise NotImplementedError
"""Create a new array

.. deprecated:: 3.0.0
Use Group.arrays.setter instead.
"""
self._sync(self._async_group.set_array(key, value))

def __repr__(self) -> str:
return f"<Group {self.store_path}>"
Expand Down Expand Up @@ -1467,9 +1517,9 @@ def group_values(self) -> Generator[Group, None]:
for _, group in self.groups():
yield group

def arrays(self) -> Generator[tuple[str, Array], None]:
for name, async_array in self._sync_iter(self._async_group.arrays()):
yield name, Array(async_array)
@property
def arrays(self) -> ArraysProxy:
return ArraysProxy(self)

def array_keys(self) -> Generator[str, None]:
for name, _ in self.arrays():
Expand Down
5 changes: 4 additions & 1 deletion src/zarr/storage/zip.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,10 @@ async def set_if_not_exists(self, key: str, value: Buffer) -> None:

async def delete(self, key: str) -> None:
# docstring inherited
raise NotImplementedError
# we choose to only raise NotImplementedError here if the key exists
# this allows the array/group APIs to avoid the overhead of existence checks
if await self.exists(key):
raise NotImplementedError

async def exists(self, key: str) -> bool:
# docstring inherited
Expand Down
52 changes: 50 additions & 2 deletions tests/v3/test_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,8 +391,56 @@ def test_group_setitem(store: Store, zarr_format: ZarrFormat) -> None:
Test the `Group.__setitem__` method.
"""
group = Group.from_store(store, zarr_format=zarr_format)
with pytest.raises(NotImplementedError):
group["key"] = 10
arr = np.ones((2, 4))
with pytest.warns(DeprecationWarning):
group["key"] = arr
assert group["key"].shape == (2, 4)
np.testing.assert_array_equal(group["key"][:], arr)

if store.supports_deletes:
key = "key"
else:
# overwriting with another array requires deletes
# for stores that don't support this, we just use a new key
key = "key2"

# overwrite with another array
arr = np.zeros((3, 5))
with pytest.warns(DeprecationWarning):
group[key] = arr
assert group[key].shape == (3, 5)
np.testing.assert_array_equal(group[key], arr)

# overwrite with a scalar
# separate bug!
# group["key"] = 1.5
# assert group["key"].shape == ()
# assert group["key"][:] == 1


def test_group_arrays_setter(store: Store, zarr_format: ZarrFormat) -> None:
"""
Test the `Group.__setitem__` method.
"""
group = Group.from_store(store, zarr_format=zarr_format)
arr = np.ones((2, 4))
group.arrays["key"] = arr
assert group["key"].shape == (2, 4)
np.testing.assert_array_equal(group["key"][:], arr)

if store.supports_deletes:
key = "key"
else:
# overwriting with another array requires deletes
# for stores that don't support this, we just use a new key
key = "key2"

# overwrite with another array
arr = np.zeros((3, 5))
with pytest.warns(DeprecationWarning):
group[key] = arr
assert group[key].shape == (3, 5)
np.testing.assert_array_equal(group[key], arr)


def test_group_contains(store: Store, zarr_format: ZarrFormat) -> None:
Expand Down