Skip to content

Commit

Permalink
feat: raise if expression changes length in .over() (#1867)
Browse files Browse the repository at this point in the history
  • Loading branch information
raisadz authored Jan 26, 2025
1 parent e9b2a1f commit 26c5cbc
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
4 changes: 4 additions & 0 deletions narwhals/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from narwhals._expression_parsing import operation_changes_length
from narwhals._expression_parsing import operation_is_order_dependent
from narwhals.dtypes import _validate_dtype
from narwhals.exceptions import LengthChangingExprError
from narwhals.expr_cat import ExprCatNamespace
from narwhals.expr_dt import ExprDateTimeNamespace
from narwhals.expr_list import ExprListNamespace
Expand Down Expand Up @@ -2702,6 +2703,9 @@ def over(self: Self, *keys: str | Iterable[str]) -> Self:
│ 3 ┆ 2 ┆ 3 │
└─────┴─────┴─────┘
"""
if self._changes_length:
msg = "`.over()` can not be used for expressions which change length."
raise LengthChangingExprError(msg)
return self.__class__(
lambda plx: self._to_compliant_expr(plx).over(flatten(keys)),
self._is_order_dependent,
Expand Down
13 changes: 13 additions & 0 deletions tests/expr_and_series/over_test.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from __future__ import annotations

import re

import pandas as pd
import pytest

import narwhals.stable.v1 as nw
from narwhals.exceptions import LengthChangingExprError
from tests.utils import PANDAS_VERSION
from tests.utils import Constructor
from tests.utils import ConstructorEager
Expand Down Expand Up @@ -207,3 +210,13 @@ def test_over_cum_reverse() -> None:
match=r"Cumulative operation with `reverse=True` is not supported",
):
nw.from_native(df).select(nw.col("b").cum_max(reverse=True).over("a"))


def test_over_raise_len_change(constructor: Constructor) -> None:
df = nw.from_native(constructor(data))

with pytest.raises(
LengthChangingExprError,
match=re.escape("`.over()` can not be used for expressions which change length."),
):
nw.from_native(df).select(nw.col("b").drop_nulls().over("a"))

0 comments on commit 26c5cbc

Please sign in to comment.