Skip to content

Commit 00e8e4a

Browse files
authored
BUG: disallow invalid dtype to CategoricalDtype._from_values_or_dtype (#32169)
1 parent 25443f0 commit 00e8e4a

File tree

3 files changed

+9
-1
lines changed

3 files changed

+9
-1
lines changed

pandas/core/dtypes/dtypes.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,8 @@ def _from_values_or_dtype(
324324
raise ValueError(
325325
"Cannot specify `categories` or `ordered` together with `dtype`."
326326
)
327+
elif not isinstance(dtype, CategoricalDtype):
328+
raise ValueError(f"Cannot not construct CategoricalDtype from {dtype}")
327329
elif is_categorical(values):
328330
# If no "dtype" was passed, use the one from "values", but honor
329331
# the "ordered" and "categories" arguments

pandas/tests/dtypes/test_dtypes.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,11 @@ def test_from_values_or_dtype_raises(self, values, categories, ordered, dtype):
127127
with pytest.raises(ValueError, match=msg):
128128
CategoricalDtype._from_values_or_dtype(values, categories, ordered, dtype)
129129

130+
def test_from_values_or_dtype_invalid_dtype(self):
131+
msg = "Cannot not construct CategoricalDtype from <class 'object'>"
132+
with pytest.raises(ValueError, match=msg):
133+
CategoricalDtype._from_values_or_dtype(None, None, None, object)
134+
130135
def test_is_dtype(self, dtype):
131136
assert CategoricalDtype.is_dtype(dtype)
132137
assert CategoricalDtype.is_dtype("category")

pandas/tests/indexes/common.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -605,7 +605,8 @@ def test_equals(self, indices):
605605
assert not indices.equals(np.array(indices))
606606

607607
# Cannot pass in non-int64 dtype to RangeIndex
608-
if not isinstance(indices, RangeIndex):
608+
if not isinstance(indices, (RangeIndex, CategoricalIndex)):
609+
# TODO: CategoricalIndex can be re-allowed following GH#32167
609610
same_values = Index(indices, dtype=object)
610611
assert indices.equals(same_values)
611612
assert same_values.equals(indices)

0 commit comments

Comments
 (0)