pola-rs/polars · error · ImportError

Required package 'torch' not installed. Please install it…

Error message

Required package 'torch' not installed.
Please install it using the command `pip install torch`.

What it means

The polars.ml.torch module requires the optional third-party package torch. Importing the module (e.g. pl.ml.torch or PolarsDataset) without torch installed raises this ImportError at module load time.

Solutions

  1. Run `pip install torch`
  2. Or install polars with the torch extra if available (e.g. pip install "polars[torch]")
  3. If torch isn't needed, avoid importing the polars.ml.torch module

Example fix

// before
from polars.ml.torch import PolarsDataset
// after
# shell: pip install torch
from polars.ml.torch import PolarsDataset
Defensive patterns

Strategy: fallback

Validate before calling

import importlib.util
if importlib.util.find_spec("torch") is None:
    raise RuntimeError("install torch: pip install torch")

Try / catch

try:
    from polars.ml.torch import PolarsDataset
except ImportError:
    PolarsDataset = None  # degrade gracefully or prompt install

Prevention

When it happens

Trigger: Importing py-polars/src/polars/ml/torch.py (or PolarsDataset) in an environment where torch is not installed.

Common situations: Deploying to a slim environment without ML extras; using to_torch/PolarsDataset features without installing the optional dependency.

Understand the failure class

Background: "X is not installed. Please install it with pip install Y": missing optional dependency errors — ImportError/ValueError raised when a library's optional extra was never installed — this error's family across 22 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/3a4d58f04fd0617f. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/ml/torch.py:29

if TYPE_CHECKING:
    import sys
    from collections.abc import Sequence

    from torch import Tensor, memory_format

    if sys.version_info >= (3, 11):
        from typing import Self
    else:
        from typing_extensions import Self
try:
    import torch
    from torch.utils.data import TensorDataset
except ImportError:
    msg = (
        "Required package 'torch' not installed.\n"
        "Please install it using the command `pip install torch`."
    )
    raise ImportError(msg) from None


__all__ = ["PolarsDataset"]


class PolarsDataset(TensorDataset):  # type: ignore[misc]
    """
    TensorDataset class specialized for use with Polars DataFrames.

    .. warning::
        This functionality is considered **unstable**. It may be changed
        at any point without it being considered a breaking change.

    Parameters
    ----------
    frame
        Polars DataFrame containing the data that will be retrieved as Tensors.
    label

View on GitHub (pinned to fe841f959e)