pydata / xarray

N-D labeled arrays and datasets in Python
https://xarray.dev
Apache License 2.0
3.63k stars 1.09k forks source link

Cannot save list attributes when it is a size-1 list #9699

Closed kgullikson88 closed 3 weeks ago

kgullikson88 commented 3 weeks ago

What happened?

I am trying to save an xr.Dataset object that has an attribute that is a list. When the list has size > 1, it works fine. But when it is a size-1 list of a string (like ['foo']) then when I open the saved dataset the list was converted into a "bare" string (i.e. just "foo" in the example above).

What did you expect to happen?

I would expect that saving the file would work the same way regardless of the list length

Minimal Complete Verifiable Example

import xarray as xr
import numpy as np

data = xr.Dataset(
    dict(
        foo=xr.DataArray(
            data=np.arange(10),
            dims=('i',),
            coords=dict(i=np.arange(10) * 10)
        )
    ),
    attrs=dict(size_1=['test'], size_2=['one', 'two'])
)
data.to_netcdf('test.nc')
roundtrip = xr.open_dataset('test.nc')

print(data.attrs['size_1'])  # gives ['test']
print(roundtrip.attrs['size_1'])  # gives 'test

MVCE confirmation

Relevant log output

No response

Anything else we need to know?

No response

Environment

INSTALLED VERSIONS ------------------ commit: None python: 3.10.14 | packaged by conda-forge | (main, Mar 20 2024, 12:45:18) [GCC 12.3.0] python-bits: 64 OS: Linux OS-release: 4.18.0-372.26.1.el8_6.x86_64 machine: x86_64 processor: x86_64 byteorder: little LC_ALL: None LANG: en_US.UTF-8 LOCALE: ('en_US', 'UTF-8') libhdf5: 1.14.3 libnetcdf: 4.9.2 xarray: 2024.6.0 pandas: 2.2.2 numpy: 1.23.5 scipy: 1.13.1 netCDF4: 1.6.5 pydap: None h5netcdf: 1.3.0 h5py: 3.11.0 zarr: 2.18.2 cftime: 1.6.3 nc_time_axis: None iris: None bottleneck: 1.4.0 dask: 2024.5.1 distributed: 2024.5.1 matplotlib: 3.8.4 cartopy: None seaborn: 0.13.2 numbagg: None fsspec: 2024.6.0 cupy: 13.2.0 pint: 0.24.1 sparse: None flox: 0.9.8 numpy_groupies: 0.10.2 setuptools: 69.2.0 pip: 24.0 conda: None pytest: 8.2.2 mypy: None IPython: 8.25.0 sphinx: 7.3.7
welcome[bot] commented 3 weeks ago

Thanks for opening your first issue here at xarray! Be sure to follow the issue template! If you have an idea for a solution, we would really welcome a Pull Request with proposed changes. See the Contributing Guide for more. It may take us a while to respond here, but we really value your contribution. Contributors like you help make xarray better. Thank you!

kmuehlbauer commented 3 weeks ago

Dupe of #4798. This is an upstream issue.