Skip to content

Problem using assign_attrs() in map() #11019

Closed

Description

@dopplershift

What is your issue?

In MetPy we have an attribute managing helper that calls DataArray.assign_attrs() within a callable passed to Dataset.map(). With recent versions of xarray, it is impossible to have the attributes assigned using assign_attrs() to be present in the result. See the following example:

import numpy as np
import xarray as xr

ds = xr.DataArray(np.zeros((3)),
    coords={'b': xr.DataArray(np.arange(3), dims='b')},
    dims=['b'], attrs={'units': 'kelvin'}, name='test').to_dataset()

def add_attr(da):
    d = da.assign_attrs(my_attr='foobar')
    return d

ds2 = ds.map(add_attr, keep_attrs=True)

print(ds2['test'].attrs)

This gives {'units': 'kelvin'}. If instead, keep_attrs=False is used, then we get {}.

This boils down to the fact that there are only two options for a DataArray processed within map():

  1. Get a direct copy (really, reference) to the original DataArray's .attrs
  2. Have .attrs set to {}

There's no option to tell map() to just leave the created DataArray alone. The only work-around I've found is to modify the original DataArray directly instead of using assign_attrs(), which is suboptimal. Things worked fine as recently as xarray 2025.6.1. I know the keep_attrs default changed to True this fall, but I'm surprised setting to False doesn't restore the previous behavior.

Activity

  1. keewis commented on Feb 22, 2026

    @keewis
    Collaborator

    for reference, you can use ds.assign({name: var.assign_attrs(...) for name, var in ds.data_vars.items()}).

    Not sure how easy it would be to define a clean and consistent API (which would be important), but I'd personally support finding a way of extending Dataset.assign_attrs and DataArray.assign_attrs to support assigning attributes to variables / coordinates.

  2. added and removed
    needs triageIssue that has not been reviewed by xarray team member
    on Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions