pola-rs/polars · error · TypeError

cannot convert Python type {qualified_type_name(el)!r} to {d

Error message

cannot convert Python type {qualified_type_name(el)!r} to {dtype!r}

What it means

maybe_cast coerces a single Python value to something valid for a target polars dtype. It maps the dtype to a Python type and calls py_type(el); if that constructor call fails (e.g. int('abc')), the failure is re-raised as TypeError naming both the value's type and the target dtype. It means the value cannot be constructed into the dtype's Python equivalent at all.

Source

Thrown at py-polars/src/polars/datatypes/convert.py:357

    )

    time_unit: TimeUnit
    if isinstance(el, datetime):
        time_unit = getattr(dtype, "time_unit", "us")
        return datetime_to_int(el, time_unit)
    elif isinstance(el, timedelta):
        time_unit = getattr(dtype, "time_unit", "us")
        return timedelta_to_int(el, time_unit)

    py_type = dtype_to_py_type(dtype)
    if not isinstance(el, py_type):
        try:
            el = py_type(el)  # type: ignore[call-arg]
        except Exception:
            from polars._utils.various import qualified_type_name

            msg = f"cannot convert Python type {qualified_type_name(el)!r} to {dtype!r}"
            raise TypeError(msg) from None
    return el

View on GitHub (pinned to df599052da)

Solutions

  1. Clean or convert offending values before construction (parse to int/float/datetime yourself)
  2. Load the dirty column as pl.String first, then .cast(target, strict=False) so bad values become nulls instead of raising
  3. Validate per-column value types before building the Series/DataFrame

Example fix

# before
s = pl.Series('n', ['1', 'oops', '3']).cast(pl.Int64)  # hits conversion error paths

# after
s = pl.Series('n', ['1', 'oops', '3']).cast(pl.Int64, strict=False)  # null for 'oops'
Defensive patterns

Strategy: try-catch

Validate before calling

from polars.datatypes.convert import dtype_to_py_type

def can_cast_value(el, dtype) -> bool:
    try:
        py_type = dtype_to_py_type(dtype)
    except NotImplementedError:
        return True  # nested dtypes handled separately
    if isinstance(el, py_type):
        return True
    try:
        py_type(el)
        return True
    except Exception:
        return False

assert can_cast_value(el, dtype), f'value {el!r} incompatible with {dtype!r}'

Try / catch

from polars.datatypes.convert import maybe_cast

try:
    v = maybe_cast(el, dtype)
except TypeError:
    v = None  # or collect the row index and report a data-quality error

Prevention

When it happens

Trigger: maybe_cast('not-a-number', pl.Int64), maybe_cast(object(), pl.Datetime), or row/element construction paths where a Python value for one column is fundamentally incompatible with the column's dtype (string into a numeric dtype, non-temporal object into Datetime).

Common situations: Building Series/DataFrames from heterogeneous rows where a stray string lands in a numeric column; pre-parsed JSON/CSV values with wrong types; custom objects expected to auto-convert.

Related errors


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