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(python): Raise for incompatible array casting in series construction #17900

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
12 changes: 12 additions & 0 deletions py-polars/polars/series/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
UInt32,
UInt64,
Unknown,
classes,
is_polars_dtype,
maybe_cast,
numpy_char_code_to_dtype,
Expand Down Expand Up @@ -274,6 +275,9 @@ def __init__(
elif dtype is not None and not is_polars_dtype(dtype):
dtype = parse_into_dtype(dtype)

if isinstance(dtype, classes.Array):
self._check_inner_array_is_compatible(dtype, values)

# Handle case where values are passed as the first argument
original_name: str | None = None
if name is None:
Expand Down Expand Up @@ -364,6 +368,14 @@ def _from_pyseries(cls, pyseries: PySeries) -> Self:
series._s = pyseries
return series

@staticmethod
def _check_inner_array_is_compatible(pl_arr: Array, target: ArrayLike) -> None:
inner = pl_arr.inner
if isinstance(target, np.ndarray):
if inner.is_integer() and np.issubdtype(target.dtype, np.floating):
msg = "Cannot cast integer array to floating point."
raise ValueError(msg)

@classmethod
@deprecate_function(
"use _import_arrow_from_c; if you are using an extension, please compile it with latest 'pyo3-polars'",
Expand Down
22 changes: 22 additions & 0 deletions py-polars/tests/unit/constructors/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,28 @@
from polars._typing import PolarsDataType


def test_dtype_array_uses_inner_dtype() -> None:
"""Issue 17743 saw passing an array dtype allow for coercion."""
a1 = np.zeros((10, 5), dtype="float32")
a1[0, 0] = 1e9
with pytest.raises(
ValueError,
match="Cannot cast integer array to floating point.",
):
pl.Series("some uint16s", a1, dtype=pl.Array(pl.UInt16, 5))

a2 = np.zeros((10, 5), dtype="float32")
with pytest.raises(
ValueError,
match="Cannot cast integer array to floating point.",
):
pl.Series("some uint16s", a2, dtype=pl.Array(pl.UInt16, 5))

# expect no error
a3 = np.zeros((10, 5), dtype="float64")
pl.Series("this should work", a3, dtype=pl.Array(pl.Float64, 5))


def test_series_mixed_dtypes_list() -> None:
values = [[0.1, 1]]

Expand Down