Skip to content

Commit d6ee8ca

Browse files
authored
Deprecate bool(ds) (#6126)
1 parent c5a2c68 commit d6ee8ca

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

doc/whats-new.rst

+5
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ Deprecations
3535
By `Tom Nicholas <https://github.com/TomNicholas>`_.
3636

3737

38+
- Coercing a dataset to bool, e.g. ``bool(ds)``, is being deprecated and will raise an
39+
error in a future version (not yet planned). For now, invoking ``Dataset.__bool__``
40+
issues a ``PendingDeprecationWarning`` (:issue:`6124`, :pull:`6126`).
41+
By `Michael Delgado <https://github.com/delgadom>`_.
42+
3843
Bug fixes
3944
~~~~~~~~~
4045
- 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`).

xarray/core/dataset.py

+8
Original file line numberDiff line numberDiff line change
@@ -1450,6 +1450,14 @@ def __len__(self) -> int:
14501450
return len(self.data_vars)
14511451

14521452
def __bool__(self) -> bool:
1453+
warnings.warn(
1454+
"coercing a Dataset to a bool will be deprecated. "
1455+
"Using bool(ds.data_vars) to check for at least one "
1456+
"data variable or using Dataset.to_array to test "
1457+
"whether array values are true is encouraged.",
1458+
PendingDeprecationWarning,
1459+
stacklevel=2,
1460+
)
14531461
return bool(self.data_vars)
14541462

14551463
def __iter__(self) -> Iterator[Hashable]:

xarray/tests/test_dataset.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -544,7 +544,9 @@ def test_properties(self):
544544
assert "aasldfjalskdfj" not in ds.variables
545545
assert "dim1" in repr(ds.variables)
546546
assert len(ds) == 3
547-
assert bool(ds)
547+
548+
with pytest.warns(PendingDeprecationWarning):
549+
assert bool(ds)
548550

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

0 commit comments

Comments
 (0)