Skip to content

Commit

Permalink
Merge pull request #319 from davidhassell/dask-bool
Browse files Browse the repository at this point in the history
dask: `Data.__bool__`
  • Loading branch information
sadielbartholomew authored Feb 10, 2022
2 parents f09b572 + f88944a commit f584ff5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
25 changes: 14 additions & 11 deletions cf/data/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions cf/test/test_Data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down

0 comments on commit f584ff5

Please sign in to comment.