Skip to content

Cannot set dataarray accessor attributes if DataArray part of Dataset  #5863

Closed
@shunt16

Description

@shunt16

Hi there, I'm trying to add some domain-specific functionality to DataArray's using register_dataarray_accessor decorator. I've run across what I think is a bug when this is applied to DataArrays that are part of a Dataset - I can't seem to set attributes. This works fine when the DataArray is not part of a Dataset. See example below:

import xarray as xr

@xr.register_dataarray_accessor("test")
class TestAccessor(object):
    def __init__(self, xarray_obj):
        self._obj = xarray_obj
        self.my_attr = "hello"

    def get_my_attr(self):
        return self.my_attr

    def set_my_attr(self, value):
    	self.my_attr = value
            

da = xr.DataArray()
ds = xr.Dataset()
ds["da"] = da

print(ds.da.test.my_attr)

ds.da.test.set_my_attr("bye")

print(ds.da.test.my_attr)

Gives

"hello"
"hello"

If the data array is not part of a dataset it works fine, so:

import xarray as xr

@xr.register_dataarray_accessor("test")
class TestAccessor(object):
    def __init__(self, xarray_obj):
        self._obj = xarray_obj
        self.my_attr = "hello"

    def get_my_attr(self):
        return self.my_attr

    def set_my_attr(self, value):
    	self.my_attr = value
            

da = xr.DataArray()

print(da.test.my_attr)

da.test.set_my_attr("bye")

print(da.test.my_attr)

Gives

"hello"
"bye"

Environment:

Output of xr.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.9.7 (default, Sep 16 2021, 08:50:36)
[Clang 10.0.0 ]
python-bits: 64
OS: Darwin
OS-release: 20.6.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: None
LANG: None
LOCALE: ('en_GB', 'UTF-8')
libhdf5: 1.12.0
libnetcdf: 4.7.4
xarray: 0.19.0
pandas: 1.3.3
numpy: 1.20.3
scipy: None
netCDF4: 1.5.7
pydap: None
h5netcdf: None
h5py: None
Nio: None
zarr: None
cftime: 1.5.1
nc_time_axis: None
PseudoNetCDF: None
rasterio: None
cfgrib: None
iris: None
bottleneck: 1.3.2
dask: None
distributed: None
matplotlib: None
cartopy: None
seaborn: None
numbagg: None
pint: None
setuptools: 58.0.4
pip: 21.2.4
conda: None
pytest: None
IPython: None
sphinx: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions