Sub topic 13
Expression simplification and type coercion
This chapter covers two rewrites the Polars optimiser makes to the expressions inside a lazy query: expression simplification and type coercion. You should already know how to build a LazyFrame, call collect(), and read explain() output, as covered in earlier chapters. Predicate and projection pushdown change which data is read. These two rewrites change the expressions themselves.
Where these rewrites sit
A lazy query is a tree of plan nodes, and each node holds expressions such as pl.col("qty") * pl.col("price"). Before the query runs, Polars walks the tree and fixes up those expressions. Type coercion makes the data types line up. Expression simplification replaces expressions with cheaper equivalents. Neither changes the result.
The diagram shows a rough order, not an exact schedule. Polars may run a pass more than once, because one rewrite can expose work for another. The set of rewrites also changes between releases. Rely on what explain() shows for your installed version, not on a fixed list.
Expression simplification
Simplification rewrites an expression into a cheaper one that gives the same answer. The clearest case is constant folding, which evaluates parts of an expression that involve only literals. Polars does this once during planning, so it doesn't repeat the work for every row.
import polars as pl
lf = pl.LazyFrame({"seconds": [30, 90, 3600]})
query = lf.with_columns(
minutes=pl.col("seconds") / (pl.lit(60) * pl.lit(1))
).filter(pl.col("seconds") > pl.lit(10) + pl.lit(20))
print(query.explain(optimized=False))
print(query.explain())
print(query.collect())In the unoptimised plan, the literal arithmetic appears as written, for example 10 + 20 inside the filter. In the optimised plan it should appear as a single literal, 30. The result is the same either way.
Polars also applies simple algebraic and boolean identities. Combining a predicate with a literal True is one example. Rewrites like this matter most in queries generated by code, where expressions are assembled from parts and often carry redundant pieces.
Simplification can only act on expressions Polars understands. A Python function inside map_elements is opaque, so Polars cannot fold or restructure it. The next chapter covers this under optimisation barriers.
Type coercion
Polars is strongly typed, and every expression has a data type that the planner works out from its inputs. When an operation mixes types, Polars coerces them. That means it inserts a cast so both sides share a type, following fixed rules. You don't write these casts yourself, but they appear in the optimised plan.
The rules you meet most often:
| Expression | Input types | Result type |
|---|---|---|
| `a + b` | Int64, Int64 | Int64 |
| `a + b` | Int64, Float64 | Float64 |
| `a + b` | Int32, Int64 | Int64 |
| `a / b` | Int64, Int64 | Float64 |
| `a // b` | Int64, Int64 | Int64 |
| `a + 1` | Int32, Python int | Int32 |
Two of these rows surprise people. True division with / always produces a float, even for two integers. A plain Python integer adapts to the integer type of the column it is combined with, so it doesn't widen an Int32 column to Int64.
You can check the result types without reading any data, because the planner computes them while resolving the plan:
import polars as pl
lf = pl.LazyFrame(
{
"qty": [1, 2, 3],
"price": [2.5, 3.0, 4.0],
"small": pl.Series([1, 2, 3], dtype=pl.Int32),
}
)
query = lf.with_columns(
total=pl.col("qty") * pl.col("price"),
half=pl.col("qty") / 2,
floor_half=pl.col("qty") // 2,
small_plus=pl.col("small") + 1,
)
print(query.collect_schema())The schema shows total and half as Float64, floor_half as Int64, and small_plus as Int32. collect_schema() returns this answer from the plan, with no execution.
Coercion in filters
Comparisons are coerced as well. Filtering an integer column against a float literal is legal, and Polars casts so that the comparison is made in a common type:
import polars as pl
lf = pl.LazyFrame({"qty": [1, 2, 3, 4]})
query = lf.filter(pl.col("qty") > 2.5)
print(query.explain())
print(query.collect())Here the result keeps rows 3 and 4. The comparison is done on a type that can represent 2.5, so the filter is not silently truncated to > 2.
Some combinations have no sensible common type. Comparing an integer column with a string is one. In that case Polars raises an error when the plan is resolved:
import polars as pl
lf = pl.LazyFrame({"qty": [1, 2, 3]})
try:
lf.filter(pl.col("qty") == "three").collect()
except pl.exceptions.PolarsError as err:
print(type(err).__name__)The error does not appear when you write the filter call. A LazyFrame records steps without checking them all, and the types are resolved at collect() or collect_schema(). In a long pipeline, call collect_schema() early in development to find type mistakes before an expensive run.
Why coercion matters for performance
Coercion is correct by construction, but the casts it inserts have a cost. If a 100-million-row Int64 column is combined with a Float64 literal on every query, Polars converts the whole column to floats each time. You can avoid this in three ways:
- Store columns in the type you will compute in.
- Use literals that match the column. Write
pl.col("qty") > 2for integer columns, not> 2.0. - Cast once, explicitly, early in the query, so later steps see the final type.
Casts also interact with predicate pushdown. A filter that compares a raw column to a literal of the same type can often be pushed into the scan. A filter that needs a cast of the column may be harder for the scan to use. Look at the scan node in explain() to see whether the predicate arrived there.
Checking what the optimiser did
Printing both plans is the quickest check:
import polars as pl
lf = pl.LazyFrame({"x": [1, 2, 3]})
query = lf.select(total=pl.col("x") * (pl.lit(2) + pl.lit(3)))
print(query.explain(optimized=False))
print(query.explain())Compare the two outputs and look for three things. Literal-only subexpressions should be folded into single values. Any cast that appears in the optimised plan but not in your code is a coercion. The scan node should show whether filters and columns were pushed down.
Common mistakes
- Expecting an error when the expression is written. Type errors in lazy queries appear at
collect()orcollect_schema(). - Using
/when you want integer division./returns a float. Use//for floor division on integers. - Mixing float literals into integer filters. The result is correct, but it can force casts that cost time on large columns.
- Assuming simplification fixes a UDF. A
map_elementscall stays opaque, so Polars cannot fold or restructure it.
Exercise
A LazyFrame has an Int32 column n. You run lf.with_columns(a=pl.col("n") + 1, b=pl.col("n") / 1).collect_schema(). What dtypes do a and b get, and why?
Show answer
a is Int32, because a plain Python integer literal adapts to the column's integer type. b is Float64, because true division with / always produces a float. collect_schema() returns these types from the plan without reading any data.
Exercise
You print query.explain(optimized=False) and query.explain() for a filter written as pl.col("seconds") > pl.lit(10) + pl.lit(20). What difference do you expect between the two plans, and does the query result change?
Show answer
The unoptimised plan shows the literal arithmetic as written, 10 + 20. The optimised plan shows the folded literal 30, which is constant folding. The result does not change, because simplification only replaces an expression with an equivalent one.