{"record":{"id":"ffc75539ce5dd2ae","repo":"pola-rs/polars","slug":"passing-expr-objects-to-the-dataframe-constructor","errorCode":null,"errorMessage":"passing Expr objects to the DataFrame constructor is not supported\n\nHint: Try evaluating the expression first using `select`, or if you meant to create an Object column containing expressions, pass a list of Expr objects instead.","messagePattern":"passing Expr objects to the DataFrame constructor is not supported\n\nHint: Try evaluating the expression first using `select`, or if you meant to create an Object column containing expressions, pass a list of Expr objects instead\\.","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/construction/dataframe.py","lineNumber":355,"sourceCode":"def _expand_dict_values(\n    data: Mapping[str, ArrayLike | NonNestedLiteral | None],\n    *,\n    schema_overrides: SchemaDict | None = None,\n    strict: bool = True,\n    order: Sequence[str] | None = None,\n    nan_to_null: bool = False,\n) -> dict[str, Series]:\n    \"\"\"Expand any scalar values in dict data (propagate literal as array).\"\"\"\n    updated_data = {}\n    if data:\n        if any(isinstance(val, pl.Expr) for val in data.values()):\n            msg = (\n                \"passing Expr objects to the DataFrame constructor is not supported\"\n                \"\\n\\nHint: Try evaluating the expression first using `select`,\"\n                \" or if you meant to create an Object column containing expressions,\"\n                \" pass a list of Expr objects instead.\"\n            )\n            raise TypeError(msg)\n\n        dtypes = schema_overrides or {}\n        data = _expand_dict_data(data, dtypes, strict=strict)\n        array_len = max((arrlen(val) or 0) for val in data.values())\n        if array_len > 0:\n            for name, val in data.items():\n                dtype = dtypes.get(name)\n                if isinstance(val, dict) and dtype != Struct:\n                    vdf = pl.DataFrame(val, strict=strict)\n                    if (\n                        vdf.height == 1\n                        and array_len > 1\n                        and all(not d.is_nested() for d in vdf.schema.values())\n                    ):\n                        s_vals = {\n                            nm: vdf[nm].extend_constant(v, n=(array_len - 1))\n                            for nm, v in val.items()\n                        }","sourceCodeStart":337,"sourceCodeEnd":373,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/_utils/construction/dataframe.py#L337-L373","documentation":"When expanding dict data for DataFrame construction, polars refuses values that are polars Expressions: an Expr is a lazy, context-dependent object with no data to place in a column, so the constructor cannot materialize it. The error tells you to evaluate the expression in a frame context (select/with_columns) or, if an Object column of expressions is genuinely intended, to wrap the Exprs in a list.","triggerScenarios":"`pl.DataFrame({\"x\": pl.col(\"a\") + 1})` or `pl.DataFrame({\"x\": pl.lit(3)})` — any dict value that is a `pl.Expr` instance. Typical when porting pandas-style code where scalar/vector expressions were passed to the constructor.","commonSituations":"Porting `pd.DataFrame({\"x\": df[\"a\"] + 1})` habits to polars; building fixtures dynamically; assuming pl.lit works as an inline constant in constructors (use plain Python scalars instead).","solutions":["Evaluate against an existing frame: `df.select((pl.col(\"a\") + 1).alias(\"x\"))` or `df.with_columns(...)`","For constants use plain Python scalars or lists: `pl.DataFrame({\"x\": [3]})`","If you truly want an Object column storing Expr objects (meta-programming/tests), wrap in a list: `pl.DataFrame({\"e\": [pl.col(\"a\")]})`"],"exampleFix":"# before\npl.DataFrame({\"x\": pl.col(\"a\") * 2})\n# TypeError: passing Expr objects to the DataFrame constructor is not supported\n\n# after — evaluate in a frame context\ndf.select((pl.col(\"a\") * 2).alias(\"x\"))\n\n# after — constant column\npl.DataFrame({\"x\": [3]})\n\n# after — deliberate Object column of Exprs\npl.DataFrame({\"exprs\": [pl.col(\"a\") * 2]})","handlingStrategy":"type-guard","validationCode":"import polars as pl\n\ndef dict_is_constructible(data: dict) -> bool:\n    return not any(isinstance(v, pl.Expr) for v in data.values())\n\nassert dict_is_constructible({\"x\": pl.col(\"a\")}) is False","typeGuard":"import polars as pl\n\ndef contains_expr(data: dict) -> bool:\n    \"\"\"True if any dict value is a polars Expr (which the constructor rejects).\"\"\"\n    return any(isinstance(v, pl.Expr) for v in data.values())","tryCatchPattern":"try:\n    df = pl.DataFrame(data)\nexcept TypeError as e:\n    if \"Expr objects\" not in str(e):\n        raise\n    df = base_df.select([v.alias(k) for k, v in data.items()])  # evaluate in frame context","preventionTips":["Use pl.lit/pl.col only inside select/with_columns/lazy contexts, never as constructor values","Pass plain Python scalars/lists for constant columns","Wrap expressions in a list only when you deliberately want an Object column of Exprs"],"tags":["expressions","dataframe-construction","type-error","lazy-evaluation"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}