Skip to content

apply_ufunc drops passed DataArray's attrs when keep_attrs=False #8047

@charlesgauthier-udm

Description

@charlesgauthier-udm

What happened?

Coming from xESMF/issues/286. When passing a DataArray to apply_ufunc with the kwarg keep_attrs = False, the attrs on the input DataArray are dropped.

Documentation states:

‘drop’ or False: empty attrs on returned xarray object.

It does not state that the input argument's attrs will be dropped.

What did you expect to happen?

I expected the input DataArray to keep its attrs when passed to apply_ufunc.

Minimal Complete Verifiable Example

import xarray as xr
import numpy as np

def magnitude(a, b):
    func = lambda x, y: np.sqrt(x ** 2 + y ** 2)
    return xr.apply_ufunc(func, a, b, keep_attrs=False)

array = xr.DataArray([1, 2, 3], coords=[("x", [0.1, 0.2, 0.3], {'axis': 'X'})])

before = array['x'].attrs
magnitude(array, -array)
after = array['x'].attrs

print(before)
print(after)

MVCE confirmation

  • Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
  • Complete example — the example is self-contained, including all data and the text of any traceback.
  • Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
  • New issue — a search of GitHub Issues suggests this is not a duplicate.

Relevant log output

No response

Anything else we need to know?

No response

Environment

Details

INSTALLED VERSIONS

commit: None
python: 3.10.11 | packaged by conda-forge | (main, May 10 2023, 18:58:44) [GCC 11.3.0]
python-bits: 64
OS: Linux
OS-release: 5.15.0-76-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: fr_CA.UTF-8
LOCALE: ('fr_CA', 'UTF-8')
libhdf5: 1.14.0
libnetcdf: 4.9.2
xarray: 2023.5.0
pandas: 2.0.2
numpy: 1.24.3
scipy: 1.10.1
netCDF4: 1.6.4
pydap: installed
h5netcdf: 1.2.0
h5py: 3.9.0
Nio: None
zarr: None
cftime: 1.6.2
nc_time_axis: None
PseudoNetCDF: None
iris: None
bottleneck: None
dask: 2023.6.0
distributed: 2023.6.0
matplotlib: 3.7.1
cartopy: None
seaborn: None
numbagg: None
fsspec: 2023.6.0
cupy: None
pint: None
sparse: 0.14.0
flox: None
numpy_groupies: None
setuptools: 67.7.2
pip: 23.1.2
conda: None
pytest: 7.3.2
mypy: None
IPython: 8.14.0
sphinx: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions