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

fix: Raise instead of panicking when casting a Series to a Struct with the wrong number of fields #21213

Merged
merged 4 commits into from
Feb 14, 2025
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
1 change: 1 addition & 0 deletions crates/polars-core/src/chunked_array/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ fn cast_single_to_struct(
fields: &[Field],
options: CastOptions,
) -> PolarsResult<Series> {
polars_ensure!(fields.len() == 1, InvalidOperation: "must specify one field in the struct");
let mut new_fields = Vec::with_capacity(fields.len());
// cast to first field dtype
let mut fields = fields.iter();
Expand Down
17 changes: 14 additions & 3 deletions py-polars/tests/unit/datatypes/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import polars as pl
import polars.selectors as cs
from polars.exceptions import InvalidOperationError
from polars.testing import assert_frame_equal, assert_series_equal

if TYPE_CHECKING:
Expand Down Expand Up @@ -923,7 +924,7 @@ def test_struct_wildcard_expansion_and_exclude() -> None:
),
]

with pytest.raises(pl.exceptions.InvalidOperationError):
with pytest.raises(InvalidOperationError):
df.lazy().select(
pl.col("meta_data").struct.with_fields(pl.field("*").exclude("user_data"))
).collect()
Expand Down Expand Up @@ -1222,7 +1223,17 @@ def test_leaf_list_eq_19613(data: Any) -> None:
def test_nested_object_raises_15237() -> None:
obj = object()
df = pl.DataFrame({"a": [obj]})
with pytest.raises(InvalidOperationError, match="nested objects are not allowed"):
df.select(pl.struct("a"))


def test_cast_to_struct_needs_field_14083() -> None:
with pytest.raises(
pl.exceptions.InvalidOperationError, match="nested objects are not allowed"
InvalidOperationError, match="must specify one field in the struct"
):
df.select(pl.struct("a"))
pl.Series([1], dtype=pl.Int32).cast(pl.Struct)

with pytest.raises(
InvalidOperationError, match="must specify one field in the struct"
):
pl.Series([1], dtype=pl.Int32).cast(pl.Struct({"a": pl.UInt8, "b": pl.UInt8}))
Loading