Skip to content

Commit

Permalink
Make __bool__ raise for more cudf objects (#16311)
Browse files Browse the repository at this point in the history
To match pandas, this PR makes `DataFrame`, `MultiIndex` and `RangeIndex` raise on `__bool__`.

Authors:
  - Matthew Roeschke (https://github.com/mroeschke)
  - GALI PREM SAGAR (https://github.com/galipremsagar)

Approvers:
  - GALI PREM SAGAR (https://github.com/galipremsagar)

URL: #16311
  • Loading branch information
mroeschke authored Jul 19, 2024
1 parent 910989e commit 6e37afc
Show file tree
Hide file tree
Showing 7 changed files with 40 additions and 7 deletions.
6 changes: 6 additions & 0 deletions python/cudf/cudf/core/_base_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ def copy(self, deep: bool = True) -> Self:
def __len__(self):
raise NotImplementedError

def __bool__(self):
raise ValueError(
f"The truth value of a {type(self).__name__} is ambiguous. Use "
"a.empty, a.bool(), a.item(), a.any() or a.all()."
)

@property
def size(self):
# The size of an index is always its length irrespective of dimension.
Expand Down
6 changes: 6 additions & 0 deletions python/cudf/cudf/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1587,6 +1587,12 @@ def __pos__(self):
def __abs__(self):
return self._unaryop("abs")

def __bool__(self):
raise ValueError(
f"The truth value of a {type(self).__name__} is ambiguous. Use "
"a.empty, a.bool(), a.item(), a.any() or a.all()."
)

# Reductions
@classmethod
@_performance_tracking
Expand Down
6 changes: 0 additions & 6 deletions python/cudf/cudf/core/single_column_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,6 @@ def shape(self) -> tuple[int]:
"""Get a tuple representing the dimensionality of the Index."""
return (len(self),)

def __bool__(self):
raise TypeError(
f"The truth value of a {type(self)} is ambiguous. Use "
"a.empty, a.bool(), a.item(), a.any() or a.all()."
)

@property # type: ignore
@_performance_tracking
def _num_columns(self) -> int:
Expand Down
2 changes: 1 addition & 1 deletion python/cudf/cudf/tests/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -1617,7 +1617,7 @@ def test_csv_reader_partial_dtype(dtype):
StringIO('"A","B","C"\n0,1,2'), dtype=dtype, usecols=["A", "C"]
)

assert names_df == header_df
assert_eq(names_df, header_df)
assert all(names_df.dtypes == ["int16", "int64"])


Expand Down
9 changes: 9 additions & 0 deletions python/cudf/cudf/tests/test_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -11100,3 +11100,12 @@ def test_from_records_with_index_no_shallow_copy():
data = np.array([(1.0, 2), (3.0, 4)], dtype=[("x", "<f8"), ("y", "<i8")])
df = cudf.DataFrame(data.view(np.recarray), index=idx)
assert df.index is idx


def test_bool_raises():
assert_exceptions_equal(
lfunc=bool,
rfunc=bool,
lfunc_args_and_kwargs=[[cudf.DataFrame()]],
rfunc_args_and_kwargs=[[pd.DataFrame()]],
)
9 changes: 9 additions & 0 deletions python/cudf/cudf/tests/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -3294,3 +3294,12 @@ def test_index_assignment_no_shallow_copy(index):
df = cudf.DataFrame(range(1))
df.index = index
assert df.index is index


def test_bool_rangeindex_raises():
assert_exceptions_equal(
lfunc=bool,
rfunc=bool,
lfunc_args_and_kwargs=[[pd.RangeIndex(0)]],
rfunc_args_and_kwargs=[[cudf.RangeIndex(0)]],
)
9 changes: 9 additions & 0 deletions python/cudf/cudf/tests/test_multiindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -2161,3 +2161,12 @@ def test_nunique(array, dropna):
result = gidx.nunique(dropna=dropna)
expected = pidx.nunique(dropna=dropna)
assert result == expected


def test_bool_raises():
assert_exceptions_equal(
lfunc=bool,
rfunc=bool,
lfunc_args_and_kwargs=[[cudf.MultiIndex.from_arrays([range(1)])]],
rfunc_args_and_kwargs=[[pd.MultiIndex.from_arrays([range(1)])]],
)

0 comments on commit 6e37afc

Please sign in to comment.