Skip to content

Commit

Permalink
Fix xr.where(..., keep_attrs=True) bug (#6461)
Browse files Browse the repository at this point in the history
* check for attrs on x

* ensure we only get attrs of x

* add whats-new
  • Loading branch information
slevang authored Apr 12, 2022
1 parent c12cb3d commit 0cd5285
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 2 deletions.
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ Bug fixes
- In the API for backends, support dimensions that express their preferred chunk sizes
as a tuple of integers. (:issue:`6333`, :pull:`6334`)
By `Stan West <https://github.com/stanwest>`_.
- Fix bug in :py:func:`where` when passing non-xarray objects with ``keep_attrs=True``. (:issue:`6444`, :pull:`6461`)
By `Sam Levang <https://github.com/slevang>`_.

Documentation
~~~~~~~~~~~~~
Expand Down
3 changes: 1 addition & 2 deletions xarray/core/computation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1825,11 +1825,10 @@ def where(cond, x, y, keep_attrs=None):
"""
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)

if keep_attrs is True:
# keep the attributes of x, the second parameter, by default to
# be consistent with the `where` method of `DataArray` and `Dataset`
keep_attrs = lambda attrs, context: attrs[1]
keep_attrs = lambda attrs, context: getattr(x, "attrs", {})

# alignment for three arguments is complicated, so don't support it yet
return apply_ufunc(
Expand Down
4 changes: 4 additions & 0 deletions xarray/tests/test_computation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1928,6 +1928,10 @@ def test_where_attrs() -> None:
expected = xr.DataArray([1, 0], dims="x", attrs={"attr": "x"})
assert_identical(expected, actual)

# ensure keep_attrs can handle scalar values
actual = xr.where(cond, 1, 0, keep_attrs=True)
assert actual.attrs == {}


@pytest.mark.parametrize("use_dask", [True, False])
@pytest.mark.parametrize("use_datetime", [True, False])
Expand Down

0 comments on commit 0cd5285

Please sign in to comment.