Skip to content

fix(attrs): update array attrs in place #2329

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 3 commits into from
Oct 11, 2024
Merged
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
9 changes: 6 additions & 3 deletions src/zarr/core/array.py
Original file line number Diff line number Diff line change
@@ -896,11 +896,14 @@ async def _delete_key(key: str) -> None:
return replace(self, metadata=new_metadata)

async def update_attributes(self, new_attributes: dict[str, JSON]) -> Self:
new_metadata = self.metadata.update_attributes(new_attributes)
# metadata.attributes is "frozen" so we simply clear and update the dict
self.metadata.attributes.clear()
self.metadata.attributes.update(new_attributes)

# Write new metadata
await self._save_metadata(new_metadata)
return replace(self, metadata=new_metadata)
await self._save_metadata(self.metadata)

return self

def __repr__(self) -> str:
return f"<AsyncArray {self.store_path} shape={self.shape} dtype={self.dtype}>"
12 changes: 12 additions & 0 deletions tests/v3/test_array.py
Original file line number Diff line number Diff line change
@@ -406,3 +406,15 @@ def test_vlen_errors() -> None:
dtype="<U4",
codecs=[BytesCodec(), VLenBytesCodec()],
)


@pytest.mark.parametrize("zarr_format", [2, 3])
def test_update_attrs(zarr_format: int) -> None:
# regression test for https://github.com/zarr-developers/zarr-python/issues/2328
store = MemoryStore({}, mode="w")
arr = Array.create(store=store, shape=5, chunk_shape=5, dtype="f8", zarr_format=zarr_format)
arr.attrs["foo"] = "bar"
assert arr.attrs["foo"] == "bar"

arr2 = zarr.open_array(store=store, zarr_format=zarr_format)
assert arr2.attrs["foo"] == "bar"
9 changes: 9 additions & 0 deletions tests/v3/test_group.py
Original file line number Diff line number Diff line change
@@ -1257,3 +1257,12 @@ def test_from_dict_extra_fields(self):
result = GroupMetadata.from_dict(data)
expected = GroupMetadata(attributes={"key": "value"}, zarr_format=2)
assert result == expected


def test_update_attrs() -> None:
# regression test for https://github.com/zarr-developers/zarr-python/issues/2328
root = Group.from_store(
MemoryStore({}, mode="w"),
)
root.attrs["foo"] = "bar"
assert root.attrs["foo"] == "bar"
Copy link
Member Author

Choose a reason for hiding this comment

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

Note: things were working fine in the Group class but I added this test here just to be safe.