Skip to content

Commit

Permalink
python: pl.struct allow eager eval (#3161)
Browse files Browse the repository at this point in the history
  • Loading branch information
ritchie46 committed Apr 16, 2022
1 parent 3467c52 commit e2f2828
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
34 changes: 33 additions & 1 deletion py-polars/polars/internals/lazy_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1420,14 +1420,43 @@ def select(
return pli.DataFrame([]).select(exprs)


def struct(exprs: Union[Sequence[Union["pli.Expr", str]], "pli.Expr"]) -> "pli.Expr":
@overload
def struct(
exprs: Union[Sequence[Union["pli.Expr", str, "pli.Series"]], "pli.Expr"],
eager: Literal[True],
) -> "pli.Series":
...


@overload
def struct(
exprs: Union[Sequence[Union["pli.Expr", str, "pli.Series"]], "pli.Expr"],
eager: Literal[False],
) -> "pli.Expr":
...


@overload
def struct(
exprs: Union[Sequence[Union["pli.Expr", str, "pli.Series"]], "pli.Expr"],
eager: bool = False,
) -> Union["pli.Expr", "pli.Series"]:
...


def struct(
exprs: Union[Sequence[Union["pli.Expr", str, "pli.Series"]], "pli.Expr"],
eager: bool = False,
) -> Union["pli.Expr", "pli.Series"]:
"""
Collect several columns into a Series of dtype Struct
Parameters
----------
exprs
Columns/Expressions to collect into a Struct
eager
Evaluate immediately
Examples
--------
Expand Down Expand Up @@ -1473,6 +1502,9 @@ def struct(exprs: Union[Sequence[Union["pli.Expr", str]], "pli.Expr"]) -> "pli.E
└─────┴───────┴─────┴───────────────────────────────┘
"""

if eager:
return pli.select(struct(exprs, eager=False)).to_series()
exprs = pli.selection_to_pyexpr_list(exprs)
return pli.wrap_expr(_as_struct(exprs))

Expand Down
5 changes: 5 additions & 0 deletions py-polars/tests/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,8 @@ def test_nested_struct() -> None:
assert isinstance(nest_l2.dtypes[0], pl.datatypes.Struct)
assert nest_l2.dtypes[0].inner_types == nest_l1.dtypes
assert isinstance(nest_l1.dtypes[0], pl.datatypes.Struct)


def test_eager_struct() -> None:
s = pl.struct([pl.Series([1, 2, 3]), pl.Series(["a", "b", "c"])], eager=True)
assert s.dtype == pl.Struct

0 comments on commit e2f2828

Please sign in to comment.