Sub topic 15
What blocks the optimiser: Python UDFs and opaque steps
This chapter assumes you can read explain() output and know the basic pushdown optimisations: predicate, projection and slice. It also assumes you are on Polars 1.x. Here you will learn which code the optimiser cannot see into, what that costs, and how to rewrite it.
Why some steps are opaque
The optimiser rewrites a plan only when it can prove the result stays the same. For native expressions such as pl.col("x") * 2 it can prove this, because it knows what the expression reads and what it produces. A Python function is different. The optimiser cannot inspect its body, so it assumes the worst.
Opaque code costs you in two ways:
- Missed rewrites. Filters and column selections may not move past the step.
- Slower execution. Each value or batch crosses into the Python interpreter. Native expressions run in parallel Rust code. Python code is limited by the GIL, the lock that lets only one thread run Python at a time.
Expression-level UDFs
Expr.map_elements calls a Python function once per value. Expr.map_batches calls it once per whole Series. In both cases the column the expression reads is still visible, for example pl.col("amount"). Only the function body is hidden.
import polars as pl
pl.DataFrame(
{
"user_id": [1, 2, 3, 4],
"amount": [10, 20, 30, 40],
"country": ["NO", "SE", "NO", "DK"],
}
).write_parquet("events.parquet")
def net(v: int) -> float:
return round(v * 0.8, 1)
udf = (
pl.scan_parquet("events.parquet")
.with_columns(
net=pl.col("amount").map_elements(net, return_dtype=pl.Float64)
)
.filter(pl.col("net") > 20)
)
native = (
pl.scan_parquet("events.parquet")
.with_columns(net=(pl.col("amount") * 0.8).round(1))
.filter(pl.col("net") > 20)
)
print(udf.explain())
print(native.explain())
print(udf.collect().equals(native.collect()))Both plans give the same rows. Two things differ:
- Optimisation. In the native plan every step is a known expression, so the optimiser can reorder and simplify freely. In the UDF plan it must treat the call as a black box.
- Speed. The UDF version pays Python call overhead on every value.
Neither plan can push the net > 20 filter into the scan. The scan has no net column, because the step computes it. This holds even for native expressions. A filter on a computed column stays above the step that computes it.
How far a filter on an untouched column (such as country) can move past a UDF step depends on your Polars version and on whether the UDF is marked element-wise. Read the plan with explain() instead of assuming.
Polars may also emit a PolarsInefficientMapWarning for simple lambdas. It suggests an equivalent native expression. Treat it as a hint to rewrite.
Frame-level UDFs: `LazyFrame.map_batches`
LazyFrame.map_batches inserts a whole-DataFrame Python function into the plan. It is the most opaque step available. Polars knows neither which columns the function uses nor whether it changes the number of rows. The method therefore exposes flags that say what the optimiser may do around it:
| Argument | Default | Meaning when set |
|---|---|---|
| `predicate_pushdown` | `True` | Filters may move past this step |
| `projection_pushdown` | `True` | Unused columns may be dropped before this step |
| `slice_pushdown` | `True` | `head` and slices may move past this step |
| `no_optimizations` | `False` | Disable all optimisations for this step |
| `schema` | `None` | Output schema. `None` means "same as input" |
The defaults are promises that you make on behalf of your function. If you are unsure, turn the promises off:
import polars as pl
def add_gross(df: pl.DataFrame) -> pl.DataFrame:
return df.with_columns(gross=pl.col("amount") * 1.25)
lf = (
pl.scan_parquet("events.parquet")
.map_batches(
add_gross,
predicate_pushdown=False,
projection_pushdown=False,
schema={
"user_id": pl.Int64,
"amount": pl.Int64,
"country": pl.String,
"gross": pl.Float64,
},
)
.select("country", "gross")
)
print(lf.explain())
print(lf.collect())With projection_pushdown=False, the scan reads every column, even though only two reach the output. That is the cost of safety.
The schema argument matters too. This function adds a column. If you left schema unset, Polars would assume the schema is unchanged. Then collect_schema() and the optimiser would work from a wrong schema.
Other steps that stop the optimiser
Not every barrier is a UDF. These patterns also limit what the optimiser can do:
- Calling
collect()in the middle of a pipeline. The first query runs to completion before later steps are known. A filter written afterwards cannot reach the scan. Keep the whole pipeline lazy and callcollect()once at the end. - Starting from
read_csvorread_parquet. These load everything eagerly. Calling.lazy()afterwards gives a plan with no file scan to push into. - Steps that depend on neighbouring rows.
head,slice,shift,cum_sumand rolling windows give different results if rows are removed first. A filter that follows such a step usually cannot move before it. - Wildcards.
pl.all()andpl.col("*")mark every column as needed. This defeats projection pushdown for that step, so name columns explicitly.
import polars as pl
# Barrier: collect() runs before the filter exists, so it is not pushed.
df = pl.scan_parquet("events.parquet").select("user_id", "country").collect()
late = df.lazy().filter(pl.col("country") == "NO")
# One plan: the filter can be pushed into the scan.
whole = (
pl.scan_parquet("events.parquet")
.select("user_id", "country")
.filter(pl.col("country") == "NO")
)
print(late.explain())
print(whole.explain())Decision flow
Native replacements
Most UDFs have a native form. Search the expression API before writing a function.
| UDF pattern | Native replacement |
|---|---|
| `map_elements(lambda v: v * 2)` | `pl.col("x") * 2` |
| `map_elements(lambda s: s.upper())` | `pl.col("s").str.to_uppercase()` |
| `if`/`else` inside a function | `pl.when(cond).then(a).otherwise(b)` |
| Dictionary lookup per value | `pl.col("k").replace_strict(mapping)` |
| Row-wise sum over columns | `pl.sum_horizontal("a", "b")` |
If no native form exists, keep the UDF but isolate it. Run the native filters and selections first so the UDF sees fewer rows and columns. Run the UDF as late as possible.
Checking your work
To confirm that a step is a barrier, compare plans. Call explain() on the query as written. Then call explain(optimized=False) and compare the two. The optimised plan should show filters and column lists inside the scan node. If they are missing, look for the first opaque step above the scan.
Exercise
A lazy query scans a Parquet file, applies LazyFrame.map_batches(fn) with default arguments, and then runs .filter(pl.col("country") == "NO"). The function fn drops all rows where amount is null. Why is it risky to leave predicate_pushdown=True here, and what should you set instead?
Show answer
With predicate_pushdown=True you promise that moving the filter before fn gives the same result. Here that may be false, because fn changes which rows exist. Set predicate_pushdown=False so the filter stays after fn. Also set schema if fn changes the columns, and use explain() to confirm where the filter ends up.
Exercise
You replace pl.col("price").map_elements(lambda p: p * 1.2) with pl.col("price") * 1.2. Name two benefits.
Show answer
The optimiser can see and rewrite the native expression, and the work runs in parallel Rust code instead of calling Python once per value.