pola-rs/polars · error · TypeError
mapping item must be a datatype or datatype expression…
Error message
mapping item must be a datatype or datatype expression; found {qualified_type_name(dtype_expr)!r} What it means
DataTypeExpr.struct_with_fields (pl.DataTypeExpr.struct_with_fields / mapping-based struct construction) requires each mapping value to be a polars DataTypeClass or DataTypeExpr. Any other value raises TypeError naming the qualified type found.
Solutions
- Use polars dtype classes, e.g. pl.Int64 instead of 'Int64'
- Use DataTypeExpr objects (e.g. from pl.dtype_expr helpers) when dynamic
- Validate mapping values with `isinstance(v, pl.DataTypeClass) or isinstance(v, pl.DataTypeExpr)`
Example fix
// before
pl.DataTypeExpr.struct_with_fields({'a': 'Int64'})
// after
pl.DataTypeExpr.struct_with_fields({'a': pl.Int64}) Defensive patterns
Strategy: type-guard
Validate before calling
for k, v in mapping.items():
if not (isinstance(v, pl.DataTypeClass) or isinstance(v, pl.DataTypeExpr)):
raise TypeError(f'{k}: {v!r} is not a polars dtype or DataTypeExpr') Type guard
def is_dtype_or_expr(v) -> TypeGuard[pl.DataTypeClass | pl.DataTypeExpr]:
return isinstance(v, (pl.DataTypeClass, pl.DataTypeExpr)) Try / catch
try:
dt = pl.DataTypeExpr.struct_with_fields(mapping)
except TypeError:
fixed = {k: getattr(pl, str(v)) for k, v in mapping.items()}
dt = pl.DataTypeExpr.struct_with_fields(fixed) Prevention
- Never use dtype-name strings; always reference pl.Int64-style classes
- Define schemas in one typed module to avoid stringly-typed mappings
When it happens
Trigger: Building a struct DataTypeExpr from a mapping whose values include plain strings like 'Int64', Python builtins (int, float), or None instead of polars dtypes.
Common situations: Confusing dtype-name strings with dtype classes; copying schemas defined as {name: 'Int64'} string dictionaries from other frameworks.
Understand the failure class
Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.
Related errors
- arr.to_struct() got a str instead of a list. hint: pass
- cannot call `map_groups` when filtering groups with `having`
- cannot call `map_groups` when grouping by an expression
- cannot call `map_groups` when grouping by named expressions
- cannot set Series of dtype
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/44d5212750b01dd9.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/functions/datatype.py:115
"""
Create a new datatype expression that represents a Struct datatype.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
"""
from polars._plr import PyDataTypeExpr
def preprocess(dtype_expr: PolarsDataType | pl.DataTypeExpr) -> PyDataTypeExpr:
if isinstance(dtype_expr, pl.DataType):
return dtype_expr.to_dtype_expr()._pydatatype_expr
if isinstance(dtype_expr, pl.DataTypeClass):
return dtype_expr.to_dtype_expr()._pydatatype_expr
elif isinstance(dtype_expr, pl.DataTypeExpr):
return dtype_expr._pydatatype_expr
else:
msg = f"mapping item must be a datatype or datatype expression; found {qualified_type_name(dtype_expr)!r}"
raise TypeError(msg)
fields = [(name, preprocess(dtype_expr)) for (name, dtype_expr) in mapping.items()]
return pl.DataTypeExpr._from_pydatatype_expr(
PyDataTypeExpr.struct_with_fields(fields)
)
View on GitHub (pinned to fe841f959e)