Skip to content

Commit 124706c

Browse files
committed
feat: Support ncs.by_name("name").meta.output_name()
1 parent d829677 commit 124706c

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

narwhals/_plan/meta.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
from narwhals._plan import expressions as ir
1414
from narwhals._plan._guards import is_literal
15+
from narwhals._plan.expressions import selectors as cs
1516
from narwhals._plan.expressions.literal import is_literal_scalar
1617
from narwhals._plan.expressions.namespace import IRNamespace
1718
from narwhals.exceptions import ComputeError, InvalidOperationError
@@ -143,6 +144,17 @@ def _expr_output_name(expr: ir.ExprIR, /) -> str | ComputeError:
143144
if isinstance(e, ir.KeepName):
144145
msg = "cannot determine output column without a context for this expression"
145146
return ComputeError(msg)
147+
# https://github.com/pola-rs/polars/pull/24064
148+
if isinstance(e, ir.SelectorIR):
149+
# Selector with single `by_name` is fine.
150+
if (
151+
isinstance(e, ir.RootSelector)
152+
and isinstance(e.selector, cs.ByName)
153+
and len(e.selector.names) == 1
154+
):
155+
return e.selector.names[0]
156+
# Other selectors aren't possible right now.
157+
break
146158
continue
147159
msg = (
148160
f"unable to find root column name for expr '{expr!r}' when calling 'output_name'"

tests/plan/meta_test.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -327,13 +327,15 @@ def test_struct_field_output_name_24003() -> None:
327327
assert nwp.col("ball").struct.field("radius").meta.output_name() == "radius"
328328

329329

330-
@pytest.mark.xfail(
331-
reason="TODO: Single `cs.by_name` can return the name.", raises=ComputeError
332-
)
333330
def test_selector_by_name_single() -> None:
334331
assert ncs.by_name("foo").meta.output_name() == "foo"
335332

336333

337334
def test_selector_by_name_multiple() -> None:
338-
with pytest.raises(ComputeError):
335+
with pytest.raises(
336+
ComputeError,
337+
match=re.escape(
338+
"unable to find root column name for expr 'ncs.by_name('foo', 'bar', require_all=True)' when calling 'output_name'"
339+
),
340+
):
339341
ncs.by_name(["foo", "bar"]).meta.output_name()

0 commit comments

Comments
 (0)