diff --git a/cf/data/data.py b/cf/data/data.py index 3ec449b74d..fb5c483265 100644 --- a/cf/data/data.py +++ b/cf/data/data.py @@ -908,23 +908,26 @@ def __bool__(self): x.__bool__() <==> bool(x) - **Examples:** + **Performance** + + `__bool__` causes all delayed operations to be computed. + + **Examples** - >>> bool(Data(1)) + >>> bool(cf.Data(1.5)) True - >>> bool(Data([[False]])) + >>> bool(cf.Data([[False]])) False - >>> bool(Data([1, 2])) - ValueError: The truth value of Data with more than one element is ambiguous. Use d.any() or d.all() """ - if self._size == 1: - return bool(self.array) + size = self.size + if size != 1: + raise ValueError( + f"The truth value of a {self.__class__.__name__} with {size} " + "elements is ambiguous. Use d.any() or d.all()" + ) - raise ValueError( - "The truth value of Data with more than one element is " - "ambiguous. Use d.any() or d.all()" - ) + return bool(self.array) def __repr__(self): """Called by the `repr` built-in function. diff --git a/cf/test/test_Data.py b/cf/test/test_Data.py index c6ae1d5a2a..edf0228bcd 100644 --- a/cf/test/test_Data.py +++ b/cf/test/test_Data.py @@ -3776,6 +3776,21 @@ def test_Data_zeros(self): self.assertEqual(d.dtype, dtype_out) self.assertTrue((d.array == np.zeros(shape, dtype=dtype_in)).all()) + def test_Data__bool__(self): + for x in (1, 1.5, True, "x"): + self.assertTrue(bool(cf.Data(x))) + self.assertTrue(bool(cf.Data([[x]]))) + + for x in (0, 0.0, False, ""): + self.assertFalse(bool(cf.Data(x))) + self.assertFalse(bool(cf.Data([[x]]))) + + with self.assertRaises(ValueError): + bool(cf.Data([])) + + with self.assertRaises(ValueError): + bool(cf.Data([1, 2])) + if __name__ == "__main__": print("Run date:", datetime.datetime.now())