Repository: narwhals-dev/narwhals
Pull request #1347 (2024-11-10 12:40:53)

fix: Fix `nw.lit` out names
<!--
# Thanks for contributing a pull request! 
## Please make sure you see our contribution guidelines: https://github.com/narwhals-dev/narwhals/blob/main/CONTRIBUTING.md
-->

## What type of PR is this? (check all applicable)

- [ ] 💾 Refactor
- [ ] ✨ Feature
- [x] 🐛 Bug Fix
- [ ] 🔧 Optimization
- [ ] 📝 Documentation
- [ ] ✅ Test
- [ ] 🐳 Other

## Related issues 

- Closes https://github.com/narwhals-dev/narwhals/issues/1346

## Checklist

- [x] Code follows style guide (ruff)
- [x] Tests added 
- [x] Documented the changes

## If you have comments or can explain your changes, please do so below.
Makes output names out of `nw.lit` be consistent with `polars`'s `"literal"` across backends. Updates docstrings for `nw.lit` by not aliasing column name to possibly make that clearer.


Patch:
diff --git a/narwhals/_arrow/namespace.py b/narwhals/_arrow/namespace.py
index c03fc723..120242fa 100644
--- a/narwhals/_arrow/namespace.py
+++ b/narwhals/_arrow/namespace.py
@@ -152,7 +152,7 @@ class ArrowNamespace:
         def _lit_arrow_series(_: ArrowDataFrame) -> ArrowSeries:
             arrow_series = ArrowSeries._from_iterable(
                 data=[value],
-                name="lit",
+                name="literal",
                 backend_version=self._backend_version,
                 dtypes=self._dtypes,
             )
@@ -165,7 +165,7 @@ class ArrowNamespace:
             depth=0,
             function_name="lit",
             root_names=None,
-            output_names=["lit"],
+            output_names=[_lit_arrow_series.__name__],
             backend_version=self._backend_version,
             dtypes=self._dtypes,
         )
diff --git a/narwhals/_dask/namespace.py b/narwhals/_dask/namespace.py
index 08fa283e..04365e51 100644
--- a/narwhals/_dask/namespace.py
+++ b/narwhals/_dask/namespace.py
@@ -76,14 +76,14 @@ class DaskNamespace:
 
         return DaskExpr(
             lambda df: [
-                df._native_frame.assign(lit=value)
-                .loc[:, "lit"]
+                df._native_frame.assign(literal=value)
+                .loc[:, "literal"]
                 .pipe(convert_if_dtype, dtype)
             ],
             depth=0,
             function_name="lit",
             root_names=None,
-            output_names=["lit"],
+            output_names=["literal"],
             returns_scalar=False,
             backend_version=self._backend_version,
             dtypes=self._dtypes,
diff --git a/narwhals/_pandas_like/namespace.py b/narwhals/_pandas_like/namespace.py
index 5646a5f1..c3ca204a 100644
--- a/narwhals/_pandas_like/namespace.py
+++ b/narwhals/_pandas_like/namespace.py
@@ -139,7 +139,7 @@ class PandasLikeNamespace:
         def _lit_pandas_series(df: PandasLikeDataFrame) -> PandasLikeSeries:
             pandas_series = PandasLikeSeries._from_iterable(
                 data=[value],
-                name="lit",
+                name="literal",
                 index=df._native_frame.index[0:1],
                 implementation=self._implementation,
                 backend_version=self._backend_version,
@@ -154,7 +154,7 @@ class PandasLikeNamespace:
             depth=0,
             function_name="lit",
             root_names=None,
-            output_names=["lit"],
+            output_names=[_lit_pandas_series.__name__],
             implementation=self._implementation,
             backend_version=self._backend_version,
             dtypes=self._dtypes,
diff --git a/narwhals/expr.py b/narwhals/expr.py
index 593f8ad7..9349dd7d 100644
--- a/narwhals/expr.py
+++ b/narwhals/expr.py
@@ -5197,31 +5197,31 @@ def lit(value: Any, dtype: DType | None = None) -> Expr:
 
         >>> @nw.narwhalify
         ... def func(df):
-        ...     return df.with_columns(nw.lit(3).alias("b"))
+        ...     return df.with_columns(nw.lit(3))
 
         We can pass any supported library such as Pandas, Polars, or PyArrow to `func`:
 
         >>> func(df_pd)
-           a  b
+           a  literal
         0  1  3
         1  2  3
         >>> func(df_pl)
         shape: (2, 2)
-        ┌─────┬─────┐
-        │ a   ┆ b   │
-        │ --- ┆ --- │
-        │ i64 ┆ i32 │
-        ╞═════╪═════╡
-        │ 1   ┆ 3   │
-        │ 2   ┆ 3   │
-        └─────┴─────┘
+        ┌─────┬─────────┐
+        │ a   ┆ literal │
+        │ --- ┆ ---     │
+        │ i64 ┆ i32     │
+        ╞═════╪═════════╡
+        │ 1   ┆ 3       │
+        │ 2   ┆ 3       │
+        └─────┴─────────┘
         >>> func(df_pa)
         pyarrow.Table
         a: int64
-        b: int64
+        literal: int64
         ----
         a: [[1,2]]
-        b: [[3,3]]
+        literal: [[3,3]]
     """
     if is_numpy_array(value):
         msg = (
diff --git a/narwhals/stable/v1/__init__.py b/narwhals/stable/v1/__init__.py
index fca13071..85e226e9 100644
--- a/narwhals/stable/v1/__init__.py
+++ b/narwhals/stable/v1/__init__.py
@@ -1447,31 +1447,31 @@ def lit(value: Any, dtype: DType | None = None) -> Expr:
 
         >>> @nw.narwhalify
         ... def func(df):
-        ...     return df.with_columns(nw.lit(3).alias("b"))
+        ...     return df.with_columns(nw.lit(3))
 
         We can pass any supported library such as Pandas, Polars, or PyArrow to `func`:
 
         >>> func(df_pd)
-           a  b
+           a  literal
         0  1  3
         1  2  3
         >>> func(df_pl)
         shape: (2, 2)
-        ┌─────┬─────┐
-        │ a   ┆ b   │
-        │ --- ┆ --- │
-        │ i64 ┆ i32 │
-        ╞═════╪═════╡
-        │ 1   ┆ 3   │
-        │ 2   ┆ 3   │
-        └─────┴─────┘
+        ┌─────┬─────────┐
+        │ a   ┆ literal │
+        │ --- ┆ ---     │
+        │ i64 ┆ i32     │
+        ╞═════╪═════════╡
+        │ 1   ┆ 3       │
+        │ 2   ┆ 3       │
+        └─────┴─────────┘
         >>> func(df_pa)
         pyarrow.Table
         a: int64
-        b: int64
+        literal: int64
         ----
         a: [[1,2]]
-        b: [[3,3]]
+        literal: [[3,3]]
     """
     return _stableify(nw.lit(value, dtype))
 


Test patch:
diff --git a/tests/frame/lit_test.py b/tests/frame/lit_test.py
index b30233fb..2b0332a5 100644
--- a/tests/frame/lit_test.py
+++ b/tests/frame/lit_test.py
@@ -50,3 +50,15 @@ def test_lit_error(constructor: Constructor) -> None:
         NotImplementedError, match="Nested datatypes are not supported yet."
     ):
         _ = df.with_columns(nw.lit([1, 2]).alias("lit"))
+
+
+def test_lit_out_name(constructor: Constructor) -> None:
+    data = {"a": [1, 3, 2]}
+    df_raw = constructor(data)
+    df = nw.from_native(df_raw).lazy()
+    result = df.with_columns(nw.lit(2))
+    expected = {
+        "a": [1, 3, 2],
+        "literal": [2, 2, 2],
+    }
+    assert_equal_data(result, expected)