Sub topic 6
Knowing the schema without running the query
This chapter assumes you can build a LazyFrame and call collect() on it. It also assumes you know what a schema is: an ordered mapping from column names to data types. The question here is how to read the schema of a lazy query's result without running the query.
Why a lazy query can know its schema
A LazyFrame holds a logical plan, not data. Each node in that plan can say what columns it outputs:
- A source node, such as an in-memory frame or a file scan, knows its own columns and types.
- A
selectnode outputs the columns its expressions produce. - A
with_columnsnode outputs the input columns plus the new or replaced ones. - A
group_bynode outputs the keys plus the aggregations.
Polars walks the plan from the source upward and applies each node's rule. The result is the schema the query would produce. No rows are processed in any step.
Using collect_schema()
LazyFrame.collect_schema() returns a Schema object. It behaves like an ordered dictionary of column name to dtype, and it also has names(), dtypes() and len() helpers.
import polars as pl
lf = (
pl.LazyFrame({
"city": ["Oslo", "Lima", "Cairo"],
"temp": [3.0, 19.5, 28.0],
})
.with_columns(
temp_f=pl.col("temp") * 9 / 5 + 32,
hot=pl.col("temp") > 20,
)
.select("city", "temp_f", "hot")
)
schema = lf.collect_schema()
print(schema)
print(schema.names())
print(schema["temp_f"])The output lists city as String, temp_f as Float64 and hot as Boolean. The query never ran. Polars only worked out the type each expression would produce. For example, a comparison gives Boolean, and a float multiplied by integer literals stays Float64.
The older attributes: schema, columns, dtypes, width
LazyFrame also has .schema, .columns, .dtypes and .width. All four need the resolved schema, and they look like cheap attribute reads. In current Polars versions they emit a PerformanceWarning that points you to collect_schema().
The warning exists because resolution can cost something. For a long plan it walks every node. For a file scan it may touch the file. collect_schema() is an explicit method call, so the cost is visible in your code. If you need several facts about the result, call it once and reuse the object:
schema = lf.collect_schema()
names = schema.names()
n_cols = len(schema)Schemas from files
For a file scan, the source node has to get its schema from the file. How it does that depends on the format.
| Source | Where the schema comes from | Cost of resolution |
|---|---|---|
| `scan_parquet` | Parquet footer metadata, which stores column names and types | Small. Reads the footer, not the data. |
| `scan_csv` | Inferred from a sample of rows | Reads rows up to `infer_schema_length` (default 100). |
| `scan_ipc` | The Arrow IPC header | Small. |
| In-memory `LazyFrame` | The frame itself | None. |
CSV is the case that needs care, because a CSV file stores no types. Polars guesses from the first rows. The guess can be wrong if a column looks like integers early on and holds decimals or text later.
You can control the guess with scan_csv arguments:
import tempfile
from pathlib import Path
import polars as pl
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "orders.csv"
path.write_text("id,amount,region\n1,10,EU\n2,20,US\n3,30,EU\n")
inferred = pl.scan_csv(path)
print(inferred.collect_schema())
explicit = pl.scan_csv(
path,
schema_overrides={"amount": pl.Float64},
)
print(explicit.collect_schema())With inference, amount comes out as Int64. With the override it is Float64, and every later step in the plan sees Float64. Two arguments matter most:
schema_overridesfixes the dtype of chosen columns and leaves the rest to inference.infer_schema_lengthsets how many rows are sampled. A larger value costs more at resolution time.Nonescans the whole file, which defeats the point of a cheap schema.
If you pass a full schema= argument, Polars does no inference. That is the most predictable choice for production pipelines where the file layout is known.
Errors show up at resolution time
Because resolution checks every expression against the columns available at that point, many mistakes are caught without running the query. A reference to a missing column is the common one:
import polars as pl
lf = pl.LazyFrame({"a": [1, 2, 3]})
bad = lf.select(pl.col("a"), pl.col("b"))
try:
bad.collect_schema()
except pl.exceptions.ColumnNotFoundError as err:
print("caught:", type(err).__name__)This works as a cheap validation step. If a pipeline reads a large file and applies many steps, calling collect_schema() first checks that the plan is consistent before any heavy work starts. Type problems, such as applying a string method to a numeric column, are reported the same way.
The same resolution runs inside collect(). Calling it early only moves the error to an earlier, cheaper point.
When the schema cannot be known
Resolution needs each node to describe its output from its input alone. A few cases break that:
- Python functions. Polars cannot look inside a lambda in
map_elements. You must declare the output type withreturn_dtype. Without it, Polars has to guess, and the guess may be wrong or produce a warning. - Data-dependent output columns. An operation whose column names depend on the values in the data cannot be resolved without reading the data.
pivotis the standard example. It exists onDataFramebut not onLazyFramefor this reason. - Wrong declarations. If you declare
return_dtype=pl.Int64and the function returns strings, the plan resolves fine and fails when the query runs.
import polars as pl
lf = pl.LazyFrame({"x": [1, 2, 3]}).with_columns(
y=pl.col("x").map_elements(lambda v: v * 2, return_dtype=pl.Int64)
)
print(lf.collect_schema())Here the schema is x: Int64, y: Int64, and it comes from your declaration, not from running the function. This is also the same opacity covered later under optimisation barriers: the optimiser takes the declared type on trust.
Practical uses
- Validating inputs. Compare
collect_schema()against an expectedpl.Schemabefore running an expensive job. - Building queries from column names. Select every numeric column by reading the dtypes from the schema, or use selectors, which resolve against the schema too.
- Checking a refactor. After changing a query, confirm the output schema is unchanged without computing anything.
import polars as pl
lf = pl.LazyFrame({"id": [1, 2], "name": ["a", "b"], "score": [0.5, 0.9]})
expected = pl.Schema({"id": pl.Int64, "name": pl.String, "score": pl.Float64})
assert lf.collect_schema() == expected
print("schema matches")Exercise
You call pl.scan_csv("data.csv").with_columns(total=pl.col("a") + pl.col("b")).collect_schema(). Does Polars read the whole file? What decides the dtype of a and b, and how can you make them Float64 regardless of what the first rows contain?
Show answer
No. Resolution reads only enough rows to infer types, up to infer_schema_length (default 100), and processes no data for the total expression. The dtypes of a and b come from that inference, and total takes whatever type adding them produces. To force Float64, pass schema_overrides={"a": pl.Float64, "b": pl.Float64} to scan_csv, or pass a full schema= to skip inference.
Exercise
Why does reading lf.columns followed by lf.dtypes on a LazyFrame trigger a PerformanceWarning, and what is the recommended replacement?
Show answer
Each attribute resolves the schema of the plan, which can be expensive for long plans or file scans, and doing it twice repeats the work. Call lf.collect_schema() once and read names and dtypes from the returned Schema, for example with schema.names() and schema.dtypes().