Skip to content

Commit

Permalink
fix(python): Fix error message for uninstantiated Enum types (pola-…
Browse files Browse the repository at this point in the history
  • Loading branch information
stinodego authored Dec 4, 2023
1 parent c1f04d1 commit d2aea50
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
2 changes: 1 addition & 1 deletion py-polars/polars/datatypes/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ def REPR_TO_DTYPE(self) -> dict[str, PolarsDataType]:
def _dtype_str_repr_safe(o: Any) -> PolarsDataType | None:
try:
return _dtype_str_repr(o.base_type()).split("[")[0]
except ValueError:
except TypeError:
return None

return {
Expand Down
12 changes: 8 additions & 4 deletions py-polars/src/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,11 @@ impl FromPyObject<'_> for Wrap<DataType> {
"Binary" => DataType::Binary,
"Boolean" => DataType::Boolean,
"Categorical" => DataType::Categorical(None),
"Enum" => {
return Err(PyTypeError::new_err(
"Enum types must be instantiated with a list of categories",
))
},
"Date" => DataType::Date,
"Datetime" => DataType::Datetime(TimeUnit::Microseconds, None),
"Time" => DataType::Time,
Expand All @@ -468,8 +473,8 @@ impl FromPyObject<'_> for Wrap<DataType> {
"Null" => DataType::Null,
"Unknown" => DataType::Unknown,
dt => {
return Err(PyValueError::new_err(format!(
"{dt} is not a recognised polars DataType.",
return Err(PyTypeError::new_err(format!(
"'{dt}' is not a Polars data type",
)))
},
}
Expand Down Expand Up @@ -539,8 +544,7 @@ impl FromPyObject<'_> for Wrap<DataType> {
},
dt => {
return Err(PyTypeError::new_err(format!(
"A {dt} object is not a recognised polars DataType. \
Hint: use the class without instantiating it.",
"'{dt}' is not a Polars data type",
)))
},
};
Expand Down
7 changes: 7 additions & 0 deletions py-polars/tests/unit/datatypes/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,10 @@ def test_extend_to_an_enum() -> None:
s.extend(s2)
assert s.len() == 8
assert s.null_count() == 1


def test_series_init_uninstantiated_enum() -> None:
with pytest.raises(
TypeError, match="Enum types must be instantiated with a list of categories"
):
pl.Series(["a", "b", "a"], dtype=pl.Enum)

0 comments on commit d2aea50

Please sign in to comment.