pola-rs/polars · error · ValueError

invalid `return_type`: {return_type!r} Expected one of: {val

Error message

invalid `return_type`: {return_type!r}
Expected one of: {valid_torch_types}

What it means

Raised by DataFrame.to_torch when `return_type` is not one of TorchExportType = Literal['tensor', 'dataset', 'dict']. Runtime strings are not checked by Literal typing, so anything else (typos, jax vocabulary, config values) falls through the dispatch chain to this final ValueError, which lists the valid options.

Source

Thrown at py-polars/src/polars/dataframe/frame.py:2531

                # return a {"label": tensor(s), "features": tensor(s)} dict
                return {
                    "label": label_frame.to_torch(),
                    "features": features_frame.to_torch(),
                }
            else:
                # return a {"col": tensor} dict
                return {srs.name: srs.to_torch() for srs in frame}

        elif return_type == "dataset":
            # return a torch Dataset object
            from polars.ml.torch import PolarsDataset

            pds_label = None if label_frame is None else label_frame.columns
            return PolarsDataset(frame, label=pds_label, features=features)
        else:
            valid_torch_types = ", ".join(get_args(TorchExportType))
            msg = f"invalid `return_type`: {return_type!r}\nExpected one of: {valid_torch_types}"
            raise ValueError(msg)

    def to_pandas(
        self,
        *,
        use_pyarrow_extension_array: bool = False,
        **kwargs: Any,
    ) -> pd.DataFrame:
        """
        Convert this DataFrame to a pandas DataFrame.

        This operation copies data if `use_pyarrow_extension_array` is not enabled.

        Parameters
        ----------
        use_pyarrow_extension_array
            Use PyArrow-backed extension arrays instead of NumPy arrays for the columns
            of the pandas DataFrame. This allows zero copy operations and preservation
            of null values. Subsequent operations on the resulting pandas DataFrame may

View on GitHub (pinned to df599052da)

Solutions

  1. Use one of 'tensor' (default), 'dataset', or 'dict'
  2. Validate external strings up front against ('tensor', 'dataset', 'dict')
  3. For jax exports use `df.to_jax(...)` with its own valid types

Example fix

# before
t = df.to_torch('tenser')

# after
t = df.to_torch('tensor')
Defensive patterns

Strategy: validation

Validate before calling

VALID_TORCH = ('tensor', 'dataset', 'dict')
if return_type not in VALID_TORCH:
    raise ValueError(f'return_type must be one of {VALID_TORCH}, got {return_type!r}')
out = df.to_torch(return_type)

Type guard

def is_torch_return_type(rt: object) -> bool:
    """to_torch only accepts 'tensor', 'dataset', or 'dict'."""
    return rt in ('tensor', 'dataset', 'dict')

Try / catch

try:
    out = df.to_torch(return_type)
except ValueError as e:
    if 'invalid `return_type`' in str(e):
        out = df.to_torch('tensor')
    else:
        raise

Prevention

When it happens

Trigger: `df.to_torch('tenser')`, `df.to_torch('array')` (jax vocabulary), `df.to_torch('Tensor')` (case mismatch), or return_type loaded from a config/CLI that isn't exactly one of the three literals.

Common situations: Parameterized export helpers where the backend string comes from YAML; mixed jax/torch codebases sharing a RETURN_TYPE constant; typos and casing errors in notebook code.

Related errors


AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16). Data as JSON: /api/errors/30dac10b1bebccf4. Report an issue: GitHub.