|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +# ruff: noqa: A002 |
| 4 | +from typing import TYPE_CHECKING |
| 5 | +from typing import Iterable |
| 6 | +from typing import Sequence |
| 7 | +from typing import TypeVar |
| 8 | + |
| 9 | +from narwhals._plan.common import is_expr |
| 10 | +from narwhals._plan.common import is_iterable_reject |
| 11 | +from narwhals.dependencies import get_polars |
| 12 | +from narwhals.dependencies import is_pandas_dataframe |
| 13 | +from narwhals.dependencies import is_pandas_series |
| 14 | +from narwhals.exceptions import InvalidIntoExprError |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + from typing import Any |
| 18 | + from typing import Iterator |
| 19 | + |
| 20 | + from typing_extensions import TypeAlias |
| 21 | + from typing_extensions import TypeIs |
| 22 | + |
| 23 | + from narwhals._plan.common import ExprIR |
| 24 | + from narwhals._plan.common import IntoExpr |
| 25 | + from narwhals._plan.common import Seq |
| 26 | + from narwhals.dtypes import DType |
| 27 | + |
| 28 | +T = TypeVar("T") |
| 29 | + |
| 30 | +_RaisesInvalidIntoExprError: TypeAlias = "Any" |
| 31 | +""" |
| 32 | +Placeholder for multiple `Iterable[IntoExpr]`. |
| 33 | +
|
| 34 | +We only support cases `a`, `b`, but the typing for most contexts is more permissive: |
| 35 | +
|
| 36 | +>>> import polars as pl |
| 37 | +>>> df = pl.DataFrame({"one": ["A", "B", "A"], "two": [1, 2, 3], "three": [4, 5, 6]}) |
| 38 | +>>> a = ("one", "two") |
| 39 | +>>> b = (["one", "two"],) |
| 40 | +>>> |
| 41 | +>>> c = ("one", ["two"]) |
| 42 | +>>> d = (["one"], "two") |
| 43 | +>>> [df.select(*into) for into in (a, b, c, d)] |
| 44 | +[shape: (3, 2) |
| 45 | + ┌─────┬─────┐ |
| 46 | + │ one ┆ two │ |
| 47 | + │ --- ┆ --- │ |
| 48 | + │ str ┆ i64 │ |
| 49 | + ╞═════╪═════╡ |
| 50 | + │ A ┆ 1 │ |
| 51 | + │ B ┆ 2 │ |
| 52 | + │ A ┆ 3 │ |
| 53 | + └─────┴─────┘, |
| 54 | + shape: (3, 2) |
| 55 | + ┌─────┬─────┐ |
| 56 | + │ one ┆ two │ |
| 57 | + │ --- ┆ --- │ |
| 58 | + │ str ┆ i64 │ |
| 59 | + ╞═════╪═════╡ |
| 60 | + │ A ┆ 1 │ |
| 61 | + │ B ┆ 2 │ |
| 62 | + │ A ┆ 3 │ |
| 63 | + └─────┴─────┘, |
| 64 | + shape: (3, 2) |
| 65 | + ┌─────┬───────────┐ |
| 66 | + │ one ┆ literal │ |
| 67 | + │ --- ┆ --- │ |
| 68 | + │ str ┆ list[str] │ |
| 69 | + ╞═════╪═══════════╡ |
| 70 | + │ A ┆ ["two"] │ |
| 71 | + │ B ┆ ["two"] │ |
| 72 | + │ A ┆ ["two"] │ |
| 73 | + └─────┴───────────┘, |
| 74 | + shape: (3, 2) |
| 75 | + ┌───────────┬─────┐ |
| 76 | + │ literal ┆ two │ |
| 77 | + │ --- ┆ --- │ |
| 78 | + │ list[str] ┆ i64 │ |
| 79 | + ╞═══════════╪═════╡ |
| 80 | + │ ["one"] ┆ 1 │ |
| 81 | + │ ["one"] ┆ 2 │ |
| 82 | + │ ["one"] ┆ 3 │ |
| 83 | + └───────────┴─────┘] |
| 84 | +""" |
| 85 | + |
| 86 | + |
| 87 | +def parse_into_expr_ir( |
| 88 | + input: IntoExpr, *, str_as_lit: bool = False, dtype: DType | None = None |
| 89 | +) -> ExprIR: |
| 90 | + """Parse a single input into an `ExprIR` node.""" |
| 91 | + from narwhals._plan import demo as nwd |
| 92 | + |
| 93 | + if is_expr(input): |
| 94 | + expr = input |
| 95 | + elif isinstance(input, str) and not str_as_lit: |
| 96 | + expr = nwd.col(input) |
| 97 | + else: |
| 98 | + expr = nwd.lit(input, dtype=dtype) |
| 99 | + return expr._ir |
| 100 | + |
| 101 | + |
| 102 | +def parse_into_seq_of_expr_ir( |
| 103 | + first_input: IntoExpr | Iterable[IntoExpr] = (), |
| 104 | + *more_inputs: IntoExpr | _RaisesInvalidIntoExprError, |
| 105 | + **named_inputs: IntoExpr, |
| 106 | +) -> Seq[ExprIR]: |
| 107 | + """Parse variadic inputs into a flat sequence of `ExprIR` nodes.""" |
| 108 | + return tuple(_parse_into_iter_expr_ir(first_input, *more_inputs, **named_inputs)) |
| 109 | + |
| 110 | + |
| 111 | +def _parse_into_iter_expr_ir( |
| 112 | + first_input: IntoExpr | Iterable[IntoExpr], |
| 113 | + *more_inputs: IntoExpr, |
| 114 | + **named_inputs: IntoExpr, |
| 115 | +) -> Iterator[ExprIR]: |
| 116 | + if not _is_empty_sequence(first_input): |
| 117 | + # NOTE: These need to be separated to introduce an intersection type |
| 118 | + # Otherwise, `str | bytes` always passes through typing |
| 119 | + if _is_iterable(first_input) and not is_iterable_reject(first_input): |
| 120 | + if more_inputs: |
| 121 | + raise _invalid_into_expr_error(first_input, more_inputs, named_inputs) |
| 122 | + else: |
| 123 | + yield from _parse_positional_inputs(first_input) |
| 124 | + else: |
| 125 | + yield parse_into_expr_ir(first_input) |
| 126 | + else: |
| 127 | + # NOTE: Passthrough case for no inputs - but gets skipped when calling next |
| 128 | + yield from () |
| 129 | + if more_inputs: |
| 130 | + yield from _parse_positional_inputs(more_inputs) |
| 131 | + if named_inputs: |
| 132 | + yield from _parse_named_inputs(named_inputs) |
| 133 | + |
| 134 | + |
| 135 | +def _parse_positional_inputs(inputs: Iterable[IntoExpr], /) -> Iterator[ExprIR]: |
| 136 | + for into in inputs: |
| 137 | + yield parse_into_expr_ir(into) |
| 138 | + |
| 139 | + |
| 140 | +def _parse_named_inputs(named_inputs: dict[str, IntoExpr], /) -> Iterator[ExprIR]: |
| 141 | + from narwhals._plan.expr import Alias |
| 142 | + |
| 143 | + for name, input in named_inputs.items(): |
| 144 | + yield Alias(expr=parse_into_expr_ir(input), name=name) |
| 145 | + |
| 146 | + |
| 147 | +def _is_iterable(obj: Iterable[T] | Any) -> TypeIs[Iterable[T]]: |
| 148 | + if is_pandas_dataframe(obj) or is_pandas_series(obj): |
| 149 | + msg = f"Expected Narwhals class or scalar, got: {type(obj)}. Perhaps you forgot a `nw.from_native` somewhere?" |
| 150 | + raise TypeError(msg) |
| 151 | + if _is_polars(obj): |
| 152 | + msg = ( |
| 153 | + f"Expected Narwhals class or scalar, got: {type(obj)}.\n\n" |
| 154 | + "Hint: Perhaps you\n" |
| 155 | + "- forgot a `nw.from_native` somewhere?\n" |
| 156 | + "- used `pl.col` instead of `nw.col`?" |
| 157 | + ) |
| 158 | + raise TypeError(msg) |
| 159 | + return isinstance(obj, Iterable) |
| 160 | + |
| 161 | + |
| 162 | +def _is_empty_sequence(obj: Any) -> bool: |
| 163 | + return isinstance(obj, Sequence) and not obj |
| 164 | + |
| 165 | + |
| 166 | +def _is_polars(obj: Any) -> bool: |
| 167 | + return (pl := get_polars()) is not None and isinstance( |
| 168 | + obj, (pl.Series, pl.Expr, pl.DataFrame, pl.LazyFrame) |
| 169 | + ) |
| 170 | + |
| 171 | + |
| 172 | +def _invalid_into_expr_error( |
| 173 | + first_input: Any, more_inputs: Any, named_inputs: Any |
| 174 | +) -> InvalidIntoExprError: |
| 175 | + msg = ( |
| 176 | + f"Passing both iterable and positional inputs is not supported.\n" |
| 177 | + f"Hint:\nInstead try collecting all arguments into a {type(first_input).__name__!r}\n" |
| 178 | + f"{first_input!r}\n{more_inputs!r}\n{named_inputs!r}" |
| 179 | + ) |
| 180 | + return InvalidIntoExprError(msg) |
0 commit comments