diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 2572651415d..2104ef29aa6 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -35,6 +35,11 @@ Deprecations By `Tom Nicholas `_. +- 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 `_. + Bug fixes ~~~~~~~~~ - Fix applying function with non-xarray arguments using :py:func:`xr.map_blocks`. diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 3fbc6154c5d..058f2214f92 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -1449,6 +1449,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]: diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index c8770601c30..40b9b31c7fa 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -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"]