pola-rs/polars · error

cannot compare to

Error message

cannot compare {self!r} to {value!r}

What it means

`DataTypeExpr.__eq__` builds a runtime expression comparing a data-type expression to another dtype expression. Only `pl.DataType` classes/instances and `DataTypeExpr` values are supported; comparing to anything else (e.g. a raw string) raises this TypeError because the comparison cannot be compiled.

Solutions

  1. Pass a Polars dtype class or instance: `pl.Int64` instead of `"Int64"` or `int`
  2. Convert the value first with `pl.DataType` constructors or `pl.datatypes` helpers
  3. Use `DataTypeExpr` objects if comparing expression-to-expression

Example fix

// before
pl.col('a').dtype == 'Int64'
// after
pl.col('a').dtype == pl.Int64
Defensive patterns

Strategy: type-guard

Validate before calling

def ensure_dtype_like(v):
    import polars as pl
    if not (isinstance(v, DataTypeExpr) or (isinstance(v, type) and issubclass(v, pl.DataType))):
        raise TypeError(f'expected polars dtype, got {v!r}')
    return v

Type guard

def is_dtype_like(v) -> bool:
    import polars as pl
    from polars.datatype_expr import DataTypeExpr
    return isinstance(v, DataTypeExpr) or (isinstance(v, type) and issubclass(v, pl.DataType))

Try / catch

try:
    result = expr == candidate
except TypeError:
    candidate = POLARS_DTYPE_MAP.get(candidate, pl.AutoDtype)
    result = expr == candidate

Prevention

When it happens

Trigger: `expr.dtype.__eq__("Int64")` or comparing a DataTypeExpr to a Python type like `int`, `str`, `list`, or an unrelated object.

Common situations: Developers pass string dtype names (`'Int64'`) or builtin types (`int`) where a Polars dtype class such as `pl.Int64` is required, often coming from JSON config or dynamic code.

Understand the failure class

Background: Type mismatch errors: IllegalArgumentException, TypeError and type guards across 150 open-source libraries — this error's family across 150 libraries.

Related errors


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

Appendix: source

Thrown at py-polars/src/polars/datatype_expr/datatype_expr.py:78

    _pydatatype_expr: PyDataTypeExpr = None  # type: ignore[assignment]
    _accessors: ClassVar[set[str]] = {
        "arr",
        "enum",
        "list",
        "struct",
    }

    def __eq__(self, value: PolarsDataType | DataTypeExpr) -> pl.Expr:  # type: ignore[override]
        cmp_with: DataTypeExpr
        if isinstance(value, pl.DataType):
            cmp_with = value.to_dtype_expr()
        elif isinstance(value, pl.DataTypeClass):
            cmp_with = value.to_dtype_expr()
        elif isinstance(value, DataTypeExpr):
            cmp_with = value
        else:
            msg = f"cannot compare {self!r} to {value!r}"
            raise TypeError(msg) from None

        return pl.Expr._from_pyexpr(
            self._pydatatype_expr.equals(cmp_with._pydatatype_expr)
        )

    def __ne__(self, value: PolarsDataType | DataTypeExpr) -> pl.Expr:  # type: ignore[override]
        return (self == value).not_()

    @classmethod
    def _from_pydatatype_expr(cls, pydatatype_expr: PyDataTypeExpr) -> DataTypeExpr:
        slf = cls()
        slf._pydatatype_expr = pydatatype_expr
        return slf

    def inner_dtype(self) -> DataTypeExpr:
        """Get the inner DataType of a List or Array."""
        return DataTypeExpr._from_pydatatype_expr(self._pydatatype_expr.inner_dtype())

View on GitHub (pinned to fe841f959e)