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

Xarray attrs (attributes) nested case propagation #63

Open
phockett opened this issue Sep 23, 2022 · 2 comments
Open

Xarray attrs (attributes) nested case propagation #63

phockett opened this issue Sep 23, 2022 · 2 comments

Comments

@phockett
Copy link
Owner

phockett commented Sep 23, 2022

Noticed that xr.copy() isn't deep-copying nested dicts (note xr.copy(deep=True) is default, see https://docs.xarray.dev/en/stable/generated/xarray.DataArray.copy.html).

Fixed for sphRealConvert() in e2ad5eb, but may need to propagate elsewhere.

E.g.

    dataCalc = dataIn.copy()   # Works for base attrs dict, but not nested dicts.
    dataCalc.attrs = copy.deepcopy(dataIn.attrs)  # THIS WORKS ALSO FOR NESTED DICT CASE

TODO: may have also fixed elsewhere? See PEMtk and IO codes for more .attrs handling methods.

TODO: check Xarray versions, tested in 2022.3.0 which is not latest.

See also pydata/xarray#2835

UPDATE: this is an issue in 2022.3.0, but not in 2022.6.0.

@phockett
Copy link
Owner Author

phockett commented Sep 23, 2022

# MINIMAL EXAMPLE, tested in XR 2022.3.0

import xarray as xr
import numpy as np

data = xr.DataArray(np.random.randn(2, 3), dims=("x", "y"), coords={"x": [10, 20]})
data.attrs['flat']='0'
data.attrs['nested']={'level1':'1'}

data2 = data.copy(deep=True)
data2.attrs['flat']='2'  # OK
# data2.attrs['nested']={'level1':'2'}  # OK
# data2.attrs['nested']['level1'] = '2'  # Fails - overwrites data
data2.attrs['nested'].update({'level1':'2'})  # Fails - overwrites data

print(data.attrs)
print(data2.attrs)

Outputs

{'flat': '0', 'nested': {'level1': '2'}}
{'flat': '2', 'nested': {'level1': '2'}}

Safe attrs copy with:

data2 = data.copy(deep=True)
data2.attrs = copy.deepcopy(data.attrs)

@phockett
Copy link
Owner Author

Manual fix applied in new sphConv functions, but may be an issue elsewhere at the moment.

Xarray >2022.6.0 should also have this issue fixed, as of 29/09/22, see pydata/xarray#2835 and pydata/xarray#7089.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant