Skip to content

Commit

Permalink
Deprecate bool(ds) (#6126)
Browse files Browse the repository at this point in the history
  • Loading branch information
delgadom authored Jan 3, 2022
1 parent c5a2c68 commit d6ee8ca
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
5 changes: 5 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ Deprecations
By `Tom Nicholas <https://github.com/TomNicholas>`_.


- Coercing a dataset to bool, e.g. ``bool(ds)``, is being deprecated and will raise an
error in a future version (not yet planned). For now, invoking ``Dataset.__bool__``
issues a ``PendingDeprecationWarning`` (:issue:`6124`, :pull:`6126`).
By `Michael Delgado <https://github.com/delgadom>`_.

Bug fixes
~~~~~~~~~
- Subclasses of ``byte`` and ``str`` (e.g. ``np.str_`` and ``np.bytes_``) will now serialise to disk rather than raising a ``ValueError: unsupported dtype for netCDF4 variable: object`` as they did previously (:pull:`5264`).
Expand Down
8 changes: 8 additions & 0 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1450,6 +1450,14 @@ def __len__(self) -> int:
return len(self.data_vars)

def __bool__(self) -> bool:
warnings.warn(
"coercing a Dataset to a bool will be deprecated. "
"Using bool(ds.data_vars) to check for at least one "
"data variable or using Dataset.to_array to test "
"whether array values are true is encouraged.",
PendingDeprecationWarning,
stacklevel=2,
)
return bool(self.data_vars)

def __iter__(self) -> Iterator[Hashable]:
Expand Down
4 changes: 3 additions & 1 deletion xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,9 @@ def test_properties(self):
assert "aasldfjalskdfj" not in ds.variables
assert "dim1" in repr(ds.variables)
assert len(ds) == 3
assert bool(ds)

with pytest.warns(PendingDeprecationWarning):
assert bool(ds)

assert list(ds.data_vars) == ["var1", "var2", "var3"]
assert list(ds.data_vars.keys()) == ["var1", "var2", "var3"]
Expand Down

0 comments on commit d6ee8ca

Please sign in to comment.