Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dask: Data.__bool__ #319

Merged
merged 1 commit into from
Feb 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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