Skip to content

Commit

Permalink
fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
EdAbati committed Oct 16, 2024
1 parent 859863f commit e9f7070
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
21 changes: 20 additions & 1 deletion narwhals/stable/v1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
from narwhals.translate import _from_native_impl
from narwhals.translate import get_native_namespace as nw_get_native_namespace
from narwhals.translate import to_native
from narwhals.translate import to_py_scalar
from narwhals.translate import to_py_scalar as _to_py_scalar_impl
from narwhals.typing import IntoDataFrameT
from narwhals.typing import IntoFrameT
from narwhals.utils import is_ordered_categorical as nw_is_ordered_categorical
Expand Down Expand Up @@ -949,6 +949,25 @@ def wrapper(*args: Any, **kwargs: Any) -> Any:
return decorator(func)


def to_py_scalar(scalar: Any) -> Any:
"""If a scalar is not Python native, tries to convert it to Python native.
Examples:
>>> import narwhals.stable.v1 as nw
>>> import pandas as pd
>>> df = nw.from_native(pd.DataFrame({"a": [1, 2, 3]}))
>>> nw.to_py_scalar(df["a"].item(0))
1
>>> import pyarrow as pa
>>> df = nw.from_native(pa.table({"a": [1, 2, 3]}))
>>> nw.to_py_scalar(df["a"].item(0))
1
>>> nw.to_py_scalar(1)
1
"""
return _stableify(_to_py_scalar_impl(scalar))


def all() -> Expr:
"""
Instantiate an expression representing all columns.
Expand Down
8 changes: 5 additions & 3 deletions tests/translate/to_py_scalar_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import narwhals as nw
from narwhals.dependencies import get_cudf
from narwhals.dependencies import get_cupy
from tests.utils import Constructor

Expand All @@ -8,7 +9,8 @@ def test_to_py_scalar(constructor_eager: Constructor) -> None:
assert nw.to_py_scalar(df["a"].item(0)) == 1


def test_to_py_scalar_cudf_array(constructor_cudf: Constructor) -> None:
df = nw.from_native(constructor_cudf({"a": [1, 2, 3]}))
if cupy := get_cupy():
def test_to_py_scalar_cudf_array() -> None:
if cudf := get_cudf():
cupy = get_cupy()
df = nw.from_native(cudf.DataFrame({"a": [1, 2, 3]}))
assert isinstance(nw.to_py_scalar(df["a"]), cupy.ndarray)

0 comments on commit e9f7070

Please sign in to comment.