Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions narwhals/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
from narwhals.utils import Version
from narwhals.utils import deprecate_native_namespace
from narwhals.utils import flatten
from narwhals.utils import import_namespace
from narwhals.utils import is_compliant_expr
from narwhals.utils import is_eager_allowed
from narwhals.utils import is_sequence_but_not_str
Expand Down Expand Up @@ -241,7 +240,7 @@ def _new_series_impl(
) -> Series[Any]:
implementation = Implementation.from_backend(backend)
if is_eager_allowed(implementation):
ns = import_namespace(version).from_backend(implementation).compliant
ns = version.namespace.from_backend(implementation).compliant
series = ns._series.from_iterable(values, name=name, context=ns, dtype=dtype)
return from_native(series, series_only=True)
elif implementation is Implementation.DASK: # pragma: no cover
Expand Down Expand Up @@ -327,7 +326,7 @@ def _from_dict_impl(
data, backend = _from_dict_no_backend(data)
implementation = Implementation.from_backend(backend)
if is_eager_allowed(implementation):
ns = import_namespace(version).from_backend(implementation).compliant
ns = version.namespace.from_backend(implementation).compliant
frame = ns._dataframe.from_dict(data, schema=schema, context=ns)
return from_native(frame, eager_only=True)
elif implementation is Implementation.UNKNOWN: # pragma: no cover
Expand Down Expand Up @@ -443,7 +442,7 @@ def _from_numpy_impl(
raise TypeError(msg)
implementation = Implementation.from_backend(backend)
if is_eager_allowed(implementation):
ns = import_namespace(version).from_backend(implementation).compliant
ns = version.namespace.from_backend(implementation).compliant
frame = ns.from_numpy(data, schema)
return from_native(frame, eager_only=True)
else: # pragma: no cover
Expand Down Expand Up @@ -531,7 +530,7 @@ def _from_arrow_impl(
raise TypeError(msg)
implementation = Implementation.from_backend(backend)
if is_eager_allowed(implementation):
ns = import_namespace(version).from_backend(implementation).compliant
ns = version.namespace.from_backend(implementation).compliant
frame = ns._dataframe.from_arrow(data, context=ns)
return from_native(frame, eager_only=True)
else: # pragma: no cover
Expand Down
19 changes: 7 additions & 12 deletions narwhals/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
from narwhals.dependencies import is_pyarrow_chunked_array
from narwhals.dependencies import is_pyarrow_table
from narwhals.utils import Version
from narwhals.utils import import_namespace

if TYPE_CHECKING:
from narwhals.dataframe import DataFrame
Expand Down Expand Up @@ -591,11 +590,9 @@ def _from_native_impl( # noqa: PLR0915
msg = "Please set `allow_series=True` or `series_only=True`"
raise TypeError(msg)
return native_object
pa_compliant = (
import_namespace(version)
.from_native_object(native_object)
.compliant.from_native(native_object)
)
pa_compliant = version.namespace.from_native_object(
native_object
).compliant.from_native(native_object)
if is_compliant_dataframe(pa_compliant):
return DataFrame(pa_compliant, level="full")
return Series(pa_compliant, level="full")
Expand Down Expand Up @@ -628,11 +625,9 @@ def _from_native_impl( # noqa: PLR0915
msg = "Cannot only use `series_only=True` or `eager_only=False` with DuckDBPyRelation"
raise TypeError(msg)
return native_object
duckdb_compliant = (
import_namespace(version)
.from_native_object(native_object)
.compliant.from_native(native_object)
)
duckdb_compliant = version.namespace.from_native_object(
native_object
).compliant.from_native(native_object)
if version is Version.V1:
return DataFrame(duckdb_compliant, level="interchange")
return LazyFrame(duckdb_compliant, level="lazy")
Expand Down Expand Up @@ -668,7 +663,7 @@ def _from_native_impl( # noqa: PLR0915

# PySpark
elif is_native_spark_like(native_object): # pragma: no cover
ns_spark = import_namespace(version).from_native_object(native_object)
ns_spark = version.namespace.from_native_object(native_object)
if series_only:
msg = f"Cannot only use `series_only` with {ns_spark.implementation._alias} DataFrame"
raise TypeError(msg)
Expand Down
38 changes: 10 additions & 28 deletions narwhals/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,16 @@ class Version(Enum):
V1 = auto()
MAIN = auto()

@property
def namespace(self) -> type[Namespace[Any]]:
if self is Version.MAIN:
from narwhals._namespace import Namespace

return Namespace
from narwhals.stable.v1._namespace import Namespace

return Namespace


class Implementation(Enum):
"""Implementation of native object (pandas, Polars, PyArrow, ...)."""
Expand Down Expand Up @@ -610,34 +620,6 @@ def import_dtypes_module(version: Version) -> DTypes:
raise AssertionError(msg)


def _into_version(obj: Version | _StoresVersion, /) -> Version:
if isinstance(obj, Version):
return obj
elif _hasattr_static(obj, "_version"):
return obj._version
msg = f"Expected {Version} but got {type(obj).__name__!r}"
raise TypeError(msg)


def import_namespace(version: Version | _StoresVersion, /) -> type[Namespace[Any]]:
version = _into_version(version)
if version is Version.MAIN:
from narwhals._namespace import Namespace

return Namespace
elif version is Version.V1:
from narwhals.stable.v1._namespace import Namespace

return Namespace
else: # pragma: no cover
msg = (
"Congratulations, you have entered unreachable code.\n"
"Please report an issue at https://github.com/narwhals-dev/narwhals/issues.\n"
f"Version: {version}"
)
raise AssertionError(msg)


def remove_prefix(text: str, prefix: str) -> str: # pragma: no cover
if text.startswith(prefix):
return text[len(prefix) :]
Expand Down
10 changes: 3 additions & 7 deletions tests/namespace_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import narwhals as nw
from narwhals._namespace import Namespace
from narwhals.utils import Version
from narwhals.utils import import_namespace

if TYPE_CHECKING:
from typing_extensions import TypeAlias
Expand Down Expand Up @@ -119,22 +118,19 @@ def test_import_namespace() -> None:

data = {"a": [1, 2, 3]}
native = pd.DataFrame(data)
ns = import_namespace(Version.V1).from_native_object(native)
ns = Version.V1.namespace.from_native_object(native)
assert ns.version is Version.V1
assert ns.implementation.is_pandas()

ns = import_namespace(Version.MAIN).from_native_object(native)
ns = Version.MAIN.namespace.from_native_object(native)
assert ns.version is Version.MAIN
assert ns.implementation.is_pandas()

compliant = ns.compliant._dataframe.from_dict(data, context=ns.compliant, schema=None)
ns_pl = import_namespace(ns.compliant).from_native_object(compliant.to_polars())
ns_pl = ns.compliant._version.namespace.from_native_object(compliant.to_polars())
assert ns_pl.version is Version.MAIN
assert ns_pl.implementation.is_polars()

with pytest.raises(TypeError):
import_namespace(data) # type: ignore[arg-type]


def test_namespace_init_subclass() -> None:
pytest.importorskip("polars")
Expand Down
Loading