Skip to content

Commit

Permalink
Allow nested dictionaries in the Zarr backend (pydata#3517)
Browse files Browse the repository at this point in the history
  • Loading branch information
eddienko committed Nov 13, 2019
1 parent 810345c commit 170ba35
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ Bug fixes
(:issue:`3402`). By `Deepak Cherian <https://github.com/dcherian/>`_
- Allow appending datetime and bool data variables to zarr stores.
(:issue:`3480`). By `Akihiro Matsukawa <https://github.com/amatsukawa/>`_.
- Allow nested dictionaries in zarr attributes.
(:issue:`3517`). By `Eduardo Gonzalez <https://github.com/eddienko>`_.

Documentation
~~~~~~~~~~~~~
Expand Down
7 changes: 5 additions & 2 deletions xarray/backends/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def check_name(name):
check_name(k)


def _validate_attrs(dataset):
def _validate_attrs(dataset, backend="netCDF"):
"""`attrs` must have a string key and a value which is either: a number,
a string, an ndarray or a list/tuple of numbers/strings.
"""
Expand All @@ -198,6 +198,9 @@ def check_attr(name, value):
"serialization to netCDF files".format(name)
)

if isinstance(value, dict) and ("zarr" in backend):
value = [value]

if not isinstance(value, (str, Number, np.ndarray, np.number, list, tuple)):
raise TypeError(
"Invalid value for attr: {} must be a number, "
Expand Down Expand Up @@ -1299,7 +1302,7 @@ def to_zarr(

# validate Dataset keys, DataArray names, and attr keys/values
_validate_dataset_names(dataset)
_validate_attrs(dataset)
_validate_attrs(dataset, backend='zarr')

if mode == "a":
_validate_datatypes_for_zarr_append(dataset)
Expand Down
7 changes: 7 additions & 0 deletions xarray/tests/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -1754,6 +1754,13 @@ def test_encoding_kwarg_fixed_width_string(self):
def test_dataset_caching(self):
super().test_dataset_caching()

def test_nested_dictionary(self):
original = create_test_data()
original.attrs["foo"] = {"bar": 1}
with self.create_zarr_target() as store_target:
original.to_zarr(store_target, mode="w")
assert_identical(original, xr.open_zarr(store_target))

def test_append_write(self):
ds, ds_to_append, _ = create_append_test_data()
with self.create_zarr_target() as store_target:
Expand Down

0 comments on commit 170ba35

Please sign in to comment.