Skip to content

Commit

Permalink
Handle numpy-only attrs in xr.where (pydata#7364)
Browse files Browse the repository at this point in the history
* check if result has attrs before trying to add them

* add whats new

* Apply suggestions from code review

Co-authored-by: Mick <[email protected]>

Co-authored-by: Mick <[email protected]>
  • Loading branch information
slevang and headtr1ck authored Dec 10, 2022
1 parent 7fc5022 commit 3b6cd2a
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 2 deletions.
3 changes: 2 additions & 1 deletion doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ Deprecations

Bug fixes
~~~~~~~~~

- Allow numpy-only objects in :py:func:`where` when ``keep_attrs=True`` (:issue:`7362`, :pull:`7364`).
By `Sam Levang <https://github.com/slevang>`_.

Documentation
~~~~~~~~~~~~~
Expand Down
2 changes: 1 addition & 1 deletion xarray/core/computation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1876,7 +1876,7 @@ def where(cond, x, y, keep_attrs=None):
# be consistent with the `where` method of `DataArray` and `Dataset`
# rebuild the attrs from x at each level of the output, which could be
# Dataset, DataArray, or Variable, and also handle coords
if keep_attrs is True:
if keep_attrs is True and hasattr(result, "attrs"):
if isinstance(y, Dataset) and not isinstance(x, Dataset):
# handle special case where x gets promoted to Dataset
result.attrs = {}
Expand Down
5 changes: 5 additions & 0 deletions xarray/tests/test_computation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1964,6 +1964,11 @@ def test_where_attrs() -> None:
expected["a"].attrs = {"attr": "x_coord"}
assert_identical(expected, actual)

# no xarray objects, handle no attrs
actual_np = xr.where(True, 0, 1, keep_attrs=True)
expected_np = np.array(0)
assert_identical(expected_np, actual_np)

# DataArray and 2 Datasets, takes attrs from x
ds_x = xr.Dataset(data_vars={"x": x}, attrs={"attr": "x_ds"})
ds_y = xr.Dataset(data_vars={"x": y}, attrs={"attr": "y_ds"})
Expand Down

0 comments on commit 3b6cd2a

Please sign in to comment.