Sub topic 15
What blocks the optimiser: Python UDFs and opaque steps
This chapter assumes you can read explain() output and know what predicate and projection pushdown do. The optimiser rewrites a plan only where it understands every step. A step it cannot inspect is an optimisation barrier, and that step limits what it can move around.
Why a Python function is opaque
A native expression such as pl.col("x") * 2 is a node in the plan. The optimiser can see which columns it reads, whether it is cheap, and whether it can be reordered or merged with other steps.
A Python function passed to map_elements is a black box. Polars knows only that it takes a value and returns one. It cannot see which columns the function really depends on, simplify its logic, or share its work with other expressions. Execution also falls back to the Python interpreter, which runs row by row and cannot use Polars' multi-threaded engine.
Comparing the two plans
The two queries below give the same result. Compare their explain() output:
import polars as pl
lf = pl.LazyFrame({"x": [1, 2, 3, 4]})
opaque = lf.with_columns(
y=pl.col("x").map_elements(lambda v: v * 2, return_dtype=pl.Int64)
).filter(pl.col("y") > 4)
native = lf.with_columns(y=pl.col("x") * 2).filter(pl.col("y") > 4)
print(opaque.explain())
print(native.explain())In the first plan the UDF appears as an opaque call that the optimiser leaves untouched. In the second plan every operation is a known expression, so the optimiser has full freedom to rewrite it. On a tiny in-memory frame the difference is small. On a Parquet scan with many columns and a selective filter, the UDF can stop the optimiser from reducing how much data is read.
The fix is usually to express the logic with native expressions:
import polars as pl
lf = pl.LazyFrame({"price": [10.0, 25.0, 40.0], "qty": [1, 2, 3]})
query = lf.with_columns(
total=pl.col("price") * pl.col("qty"),
size=pl.when(pl.col("price") > 20).then(pl.lit("big")).otherwise(pl.lit("small")),
)
print(query.collect())pl.when(...).then(...).otherwise(...) replaces most if logic that people write in lambdas. The str, dt and list namespaces cover many other cases.
Other opaque steps
LazyFrame.map_batchesruns an arbitrary Python function on the whole frame. It has parameters such aspredicate_pushdownandprojection_pushdownthat tell Polars whether the function is safe to optimise around. Set them only if you are sure.collect()followed by.lazy()ends one plan and starts another. Nothing in the second plan can push work into the first, and the intermediate result is fully materialised in memory.- Eager reads.
pl.read_csv(...).lazy()has already loaded the whole file, so there is no scan node to push filters and column selections into. Usepl.scan_csv(...).
A working rule
- Write the query with native expressions first.
- Look at
explain()to check that filters and column selections reach the scan. - Introduce a UDF only for logic that has no native equivalent, and place it as late in the query as possible, after filters have reduced the data.
Exercise
A pipeline calls pl.read_parquet("events.parquet").lazy().filter(pl.col("country") == "NO"). The filter never appears inside a scan node in explain(). Why, and what is the fix?
Show answer
read_parquet is eager. It loads the whole file before .lazy() is called, so the plan has no scan node to receive the filter. Replace it with pl.scan_parquet("events.parquet"), so the filter can be pushed into the scan and fewer rows are read.