Skip to content

Commit fde2682

Browse files
authored
fix(rust, python): don't cast nulls before trying normal cast (#6339)
1 parent dbd2f13 commit fde2682

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

polars/polars-core/src/series/mod.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -228,11 +228,16 @@ impl Series {
228228

229229
/// Cast `[Series]` to another `[DataType]`
230230
pub fn cast(&self, dtype: &DataType) -> PolarsResult<Self> {
231-
let len = self.len();
232-
if self.null_count() == len {
233-
Ok(Series::full_null(self.name(), len, dtype))
234-
} else {
235-
self.0.cast(dtype)
231+
match self.0.cast(dtype) {
232+
Ok(out) => Ok(out),
233+
Err(err) => {
234+
let len = self.len();
235+
if self.null_count() == len {
236+
Ok(Series::full_null(self.name(), len, dtype))
237+
} else {
238+
Err(err)
239+
}
240+
}
236241
}
237242
}
238243

py-polars/tests/unit/test_constructors.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,3 +626,32 @@ def test_nested_read_dict_4143() -> None:
626626
],
627627
],
628628
}
629+
630+
631+
@typing.no_type_check
632+
def test_from_records_nullable_structs() -> None:
633+
records = [
634+
{"id": 1, "items": [{"item_id": 100, "description": None}]},
635+
{"id": 1, "items": [{"item_id": 100, "description": "hi"}]},
636+
]
637+
638+
schema = [
639+
("id", pl.UInt16),
640+
(
641+
"items",
642+
pl.List(
643+
pl.Struct(
644+
[pl.Field("item_id", pl.UInt32), pl.Field("description", pl.Utf8)]
645+
)
646+
),
647+
),
648+
]
649+
650+
for columns in [schema, None]:
651+
assert pl.DataFrame(records, orient="row", columns=columns).to_dict(False) == {
652+
"id": [1, 1],
653+
"items": [
654+
[{"item_id": 100, "description": None}],
655+
[{"item_id": 100, "description": "hi"}],
656+
],
657+
}

0 commit comments

Comments
 (0)