Skip to content

[Bug]: TypeVar(s) used in nw.(BaseFrame|Series) are recursive #2239

@dangotbanned

Description

@dangotbanned

Describe the bug

Discovered during (#2236 (comment)) that we probably need to narrow the TypeVar(s) used for the narwhals (not compliant) types.

Screenshot

image

Steps or code to reproduce the bug

import polars as pl
from typing_extensions import reveal_type

import narwhals as nw

series = pl.Series([1, 2, 3])
nw_series = nw.from_native(series, series_only=True)
reveal_type(nw_series)
# Type of "nw_series" is "narwhals.series.Series[polars.series.series.Series]"

nw_series_nest_1 = nw.from_native(nw_series, series_only=True)
reveal_type(nw_series_nest_1)
# Type of "nw_series_nest_1" is "narwhals.series.Series[narwhals.series.Series[polars.series.series.Series]]"

nw_series_nest_2 = nw.from_native(nw_series_nest_1, series_only=True)
reveal_type(nw_series_nest_2)
# Type of "nw_series_nest_2" is "narwhals.series.Series[narwhals.series.Series[narwhals.series.Series[polars.series.series.Series]]]"

Expected results

The nested types shouldn't be valid and are currently inaccurate.

At runtime we have:

>>> type(nw_series_nest_1._compliant_series)
narwhals._polars.series.PolarsSeries

>>> type(nw_series_nest_2._compliant_series)
narwhals._polars.series.PolarsSeries

Actual results

nw.from_native is masking what's going on, so a simple example is to try and create that type manually.

import polars as pl

from narwhals._polars.series import PolarsSeries
from narwhals.utils import Version
from narwhals.utils import parse_version

compliant_series = PolarsSeries(
    series, backend_version=parse_version(pl), version=Version.MAIN
)
nw_series_manual = nw.Series(compliant_series, level="full")
reveal_type(nw_series_manual)
# Type of "nw_series_manual" is "Series[Unknown]"

So far, that's expected until this is resolved in #2236:

# TODO @dangotbanned: Repeat (#2119) for `CompliantSeries` to support typing
# morally: `CompliantSeries`
self._compliant_series = series.__narwhals_series__()

But now we can force the error:

>>> nw.Series(nw_series_manual, level="full")
AssertionError: Expected Polars Series or an object which implements `__narwhals_series__`, got: <class 'narwhals.series.Series'>.

Please run narwhals.show_version() and enter the output below.

275c5b6

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions