{"record":{"id":"fee533d281f1f287","repo":"pola-rs/polars","slug":"cannot-convert-python-type-qualified-type-name-el","errorCode":null,"errorMessage":"cannot convert Python type {qualified_type_name(el)!r} to {dtype!r}","messagePattern":"cannot convert Python type (.+?) to (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/datatypes/convert.py","lineNumber":366,"sourceCode":"    )\n\n    time_unit: TimeUnit\n    if isinstance(el, datetime):\n        time_unit = getattr(dtype, \"time_unit\", \"us\")\n        return datetime_to_int(el, time_unit)\n    elif isinstance(el, timedelta):\n        time_unit = getattr(dtype, \"time_unit\", \"us\")\n        return timedelta_to_int(el, time_unit)\n\n    py_type = dtype_to_py_type(dtype)\n    if not isinstance(el, py_type):\n        try:\n            el = py_type(el)  # type: ignore[call-arg]\n        except Exception:\n            from polars._utils.various import qualified_type_name\n\n            msg = f\"cannot convert Python type {qualified_type_name(el)!r} to {dtype!r}\"\n            raise TypeError(msg) from None\n    return el\n","sourceCodeStart":348,"sourceCodeEnd":368,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/datatypes/convert.py#L348-L368","documentation":"maybe_cast tries to coerce an element to the target Polars dtype's Python type; when the conversion (py_type(el)) fails, it raises TypeError naming the source Python type and target dtype. It enforces strict element-type compatibility when building Series from sequences.","triggerScenarios":"pl.Series('x', ['a', 1], dtype=pl.Int64) where 'a' cannot be int()-ed; passing None mixed with strict=False only allowing null for the right dtype; passing dicts where scalars are expected; passing arbitrary objects to numeric dtypes.","commonSituations":"Dirty CSV/JSON data with stray strings in numeric columns; mixed-type lists from parsed logs; numpy scalars of the wrong width; booleans mixed with ints under an Int dtype.","solutions":["Clean/pre-cast the data: [int(v) for v in values] or coerce with pandas/numpy beforehand.","Build the Series without a strict dtype and cast after with .cast(dtype, strict=False), filtering nulls.","Filter or fix offending rows before constructing the Series."],"exampleFix":"// before\npl.Series([\"1\", \"2\", \"oops\"], dtype=pl.Int64)  # TypeError\n// after\npl.Series([\"1\", \"2\", \"oops\"]).cast(pl.Int64, strict=False)  # null where cast fails","handlingStrategy":"try-catch","validationCode":"def castable(values, dtype) -> bool:\n    py_t = {pl.Int64: int, pl.Float64: float, pl.Utf8: str, pl.Boolean: bool}.get(dtype.base_type())\n    return py_t is None or all(isinstance(v, py_t) or v is None for v in values)","typeGuard":"def all_ints(values: list[object]) -> TypeGuard[list[int]]:\n    return all(isinstance(v, int) or v is None for v in values)","tryCatchPattern":"try:\n    s = pl.Series(values, dtype=dtype)\nexcept TypeError as e:\n    if \"cannot convert Python type\" in str(e):\n        s = pl.Series(values).cast(dtype, strict=False)\n    else:\n        raise","preventionTips":["Sanitize mixed-type data (stray strings in numeric columns) before Series construction","Use strict=False casts when data may contain unparseable values","Validate column types against the declared schema in ETL entry points"],"tags":["python","polars","dtype","type-mismatch"],"backgroundTag":"type-mismatch","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}