pola-rs/polars · error
DataTypeExpr.collect_dtype did not expect
Error message
DataTypeExpr.collect_dtype did not expect {context!r} What it means
`DataTypeExpr.collect_dtype` resolves the expression against a schema derived from the given context. Only a DataFrame's schema or a LazyFrame's collected schema is accepted; any other object (e.g. a plain Schema, dict, or Series) raises this TypeError.
Solutions
- Pass a `pl.DataFrame` or `pl.LazyFrame` as the context
- If you have a Schema/dict, wrap it: `expr.collect_dtype(pl.DataFrame(schema))`
- If you have a Series, wrap it: `expr.collect_dtype(s.to_frame())`
Example fix
// before
expr.collect_dtype(pl.Schema({'a': pl.Int64}))
// after
expr.collect_dtype(pl.DataFrame({'a': pl.Int64})) Defensive patterns
Strategy: type-guard
Validate before calling
def ensure_collect_context(ctx):
import polars as pl
if not isinstance(ctx, (pl.DataFrame, pl.LazyFrame)):
raise TypeError('collect_dtype context must be DataFrame or LazyFrame')
return ctx Type guard
def is_collect_context(ctx) -> bool:
import polars as pl
return isinstance(ctx, (pl.DataFrame, pl.LazyFrame)) Try / catch
try:
dtype = expr.collect_dtype(ctx)
except TypeError as e:
if 'did not expect' in str(e):
dtype = expr.collect_dtype(pl.DataFrame(ctx))
else:
raise Prevention
- Only pass DataFrames or LazyFrames to collect_dtype
- Wrap Series/Schemas in a DataFrame first
When it happens
Trigger: Passing something other than `pl.DataFrame` or `pl.LazyFrame` as context, e.g. `expr.collect_dtype(pl.Schema({...}))` or a Series.
Common situations: Developers attempt to resolve dtype expressions against a hand-built schema or a Series because collect_dtype's accepted context types are easy to misread.
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
- cannot compare to
- cannot use credential_provider when passing a DeltaTable…
- expected type 'int | str', got
- `format` must be one of
- `how` must be one of
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/4b3f886cd51b3a9e.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/datatype_expr/datatype_expr.py:302
... }
... )
>>> pl.dtype_of("a").collect_dtype(lf)
Int64
>>> pl.dtype_of("a").collect_dtype({"a": pl.String})
String
"""
schema: pl.Schema
if isinstance(context, pl.Schema):
schema = context
elif isinstance(context, Mapping):
schema = pl.Schema(context)
elif isinstance(context, pl.DataFrame):
schema = context.schema
elif isinstance(context, pl.LazyFrame):
schema = context.collect_schema()
else:
msg = f"DataTypeExpr.collect_dtype did not expect {context!r}"
raise TypeError(msg)
return self._pydatatype_expr.collect_dtype(schema)
View on GitHub (pinned to fe841f959e)