Skip to content

Commit

Permalink
feat(python): Raise if expression passed as scalar to DataFrame const…
Browse files Browse the repository at this point in the history
…ructor (#12916)
  • Loading branch information
stinodego committed Dec 7, 2023
1 parent 4d0c442 commit 16c5dbe
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions py-polars/polars/utils/_construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,14 @@ def _expand_dict_scalars(
"""Expand any scalar values in dict data (propagate literal as array)."""
updated_data = {}
if data:
if any(isinstance(val, pl.Expr) for val in data.values()):
raise TypeError(
"passing Expr objects to the DataFrame constructor is not supported"
"\n\nHint: Try evaluating the expression first using `select`,"
" or if you meant to create an Object column containing expressions,"
" pass a list of Expr objects instead."
)

dtypes = schema_overrides or {}
data = _expand_dict_data(data, dtypes)
array_len = max((arrlen(val) or 0) for val in data.values())
Expand Down
14 changes: 14 additions & 0 deletions py-polars/tests/unit/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1466,3 +1466,17 @@ def test_list_null_constructor() -> None:
def test_numpy_float_construction_av() -> None:
np_dict = {"a": np.float64(1)}
assert_frame_equal(pl.DataFrame(np_dict), pl.DataFrame({"a": 1.0}))


def test_df_init_dict_raise_on_expression_input() -> None:
with pytest.raises(
TypeError,
match="passing Expr objects to the DataFrame constructor is not supported",
):
pl.DataFrame({"a": pl.int_range(0, 3)})
with pytest.raises(TypeError):
pl.DataFrame({"a": pl.int_range(0, 3), "b": [3, 4, 5]})

# Passing a list of expressions is allowed
df = pl.DataFrame({"a": [pl.int_range(0, 3)]})
assert df.get_column("a").dtype == pl.Object

0 comments on commit 16c5dbe

Please sign in to comment.