pola-rs/polars · error · ImportError

Required package 'torch' not installed.\nPlease install it u

Error message

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

What it means

The polars.ml.torch module (PolarsDataset and the dataset/dataloader return types of DataFrame.to_torch) imports torch at module import time. If torch is not installed, it raises ImportError with the exact pip command to fix it.

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 df599052da)

Solutions

  1. Install it: pip install torch (or uv add torch / poetry add torch)
  2. Declare torch as an explicit project dependency wherever to_torch/PolarsDataset is used
  3. If tensors are not needed, use df.to_numpy() instead; or gate the torch-dependent code path behind an availability check

Example fix

# before
from polars.ml.torch import PolarsDataset  # ImportError in torch-less env

# after
# pip install torch
from polars.ml.torch import PolarsDataset
Defensive patterns

Strategy: validation

Validate before calling

import importlib.util

if importlib.util.find_spec('torch') is None:
    raise RuntimeError('install torch (pip install torch) before using to_torch datasets')

Type guard

import importlib.util

def torch_available() -> bool:
    return importlib.util.find_spec('torch') is not None

Try / catch

try:
    from polars.ml.torch import PolarsDataset
except ImportError as exc:
    raise RuntimeError('ML features require torch; run: pip install torch') from exc

Prevention

When it happens

Trigger: from polars.ml.torch import PolarsDataset, or df.to_torch(return_type='dataset'/'dataloader'), in an environment where torch is absent.

Common situations: Slim production/CI images without ML extras; local venvs that installed polars only; deploying code developed where torch happened to be present.

Related errors


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