Sub topic 2
Expressions: the building blocks the optimiser can inspect
This chapter assumes you can write basic Polars queries with pl.col, select, filter, with_columns and group_by. It also assumes you know that a LazyFrame builds a plan that collect() runs. Here you will see why expressions, not Python code, are what lets the optimiser reason about a query.
An expression is a description, not a result
A Polars expression (pl.Expr) is an object that describes a computation on columns. It holds no data. Writing pl.col("temp") * 2 does not multiply anything. It builds a small tree: a column reference, a literal 2, and a multiply operation joining them.
You can inspect that description without any data:
import polars as pl
expr = (pl.col("temp") * 9 / 5 + 32).alias("temp_f")
print(expr.meta.root_names()) # ['temp']
print(expr.meta.output_name()) # temp_fmeta.root_names() lists the input columns the expression reads. meta.output_name() gives the name of the column it produces. The optimiser relies on the same two facts about every expression:
- Which columns does it read?
- What does it produce?
Those answers drive the optimisations covered in later chapters. Projection pushdown needs the input columns. Predicate pushdown needs to know which columns a filter touches.
Expressions are not tied to a frame
Because an expression is only a description, you can define it once and use it in any context. A context is a method that evaluates expressions against data, such as select, with_columns, filter or group_by(...).agg. The same expression works on a DataFrame and on a LazyFrame:
import polars as pl
df = pl.DataFrame({"temp": [3.0, 19.5, 28.0]})
to_f = (pl.col("temp") * 9 / 5 + 32).alias("temp_f")
eager = df.select(to_f)
lazy = df.lazy().select(to_f).collect()
print(eager.equals(lazy)) # TrueIn the eager call, Polars evaluates to_f immediately. In the lazy call, Polars stores to_f inside a select node of the plan and evaluates it later. The expression is identical in both cases. Only the timing changes.
Every node in this tree is an operation Polars knows. The optimiser can see that the whole expression reads only temp. It can also fold constants, which is covered in the chapter on expression simplification.
Why expressions are inspectable and Python functions are not
The tree above is made of native operations. Polars can read it, rewrite it, split it across threads, and move it around a plan. A Python function is different. If you pass lambda v: v * 2 to map_elements, the plan holds a call into Python. Polars cannot tell which columns the lambda reads or what it does, so it has to treat it as a black box.
The next two chapters build on this. For now, keep the rule: prefer native expressions. They are what the optimiser can inspect.
Expression expansion
Many expressions describe more than one output column. pl.all(), pl.col("a", "b"), a regular expression such as pl.col("^t.*$"), and a dtype selector such as pl.col(pl.Int64) all expand into several concrete expressions. Polars does this expansion while it resolves the plan, using the frame's schema:
import polars as pl
lf = pl.LazyFrame({
"a": [1, 2],
"b": [3, 4],
"name": ["x", "y"],
})
query = lf.select(pl.col(pl.Int64) * 10)
print(query.collect_schema().names()) # ['a', 'b']
print(query.collect())pl.col(pl.Int64) * 10 became two expressions, col("a") * 10 and col("b") * 10. The name column is not touched. The expansion happened without running the query, because it needs only the schema. The next chapters cover schema resolution in more detail.
Output names
Every expression in a context must produce a uniquely named column. Polars decides the name by a few rules:
- A column reference keeps its name.
- A binary operation takes the name of its left-most input, so
pl.col("a") + pl.col("b")is nameda. - A literal on its own is named
literal. aliasoverrides the name.
The second rule causes a common error. Two expressions that both produce the name a in the same select raise a duplicate-name error:
import polars as pl
df = pl.DataFrame({"a": [1, 2], "b": [3, 4]})
# Raises DuplicateError: both outputs would be named "a".
# df.select(pl.col("a") + 1, pl.col("a") * 2)
fixed = df.select(
(pl.col("a") + 1).alias("a_plus"),
(pl.col("a") * 2).alias("a_double"),
)
print(fixed)With a lazy frame the error surfaces when the schema is resolved, which can be before any data is read. That early failure is a benefit of lazy planning.
Expressions inside one context run together
The expressions you pass to a single select or with_columns call are independent of each other. Polars may evaluate them in parallel. They also cannot see each other's results from the same call:
import polars as pl
df = pl.DataFrame({"x": [1, 2, 3]})
# 'y' does not exist yet when 'z' is evaluated, so this raises ColumnNotFoundError.
# df.with_columns(y=pl.col("x") * 2, z=pl.col("y") + 1)
step = df.with_columns(y=pl.col("x") * 2).with_columns(z=pl.col("y") + 1)
print(step)Chaining two with_columns calls creates two nodes in the plan. The optimiser can still see through both of them, as long as every step is native. This independence is what makes parallel execution safe, and it also makes it easy for the optimiser to spot repeated work. A later chapter on common subexpression elimination covers that.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Treating `pl.col("a") * 2` as a value | It is an `Expr`, so printing it shows a description, not numbers | Use it inside `select`, `with_columns`, `filter` or `agg` |
| Two outputs with the same name | A duplicate-name error | Add `.alias(...)` |
| Referring to a column created in the same `with_columns` call | `ColumnNotFoundError` | Split into two calls |
| Using `map_elements` where a native expression exists | Slower, and the optimiser has less freedom | Use native operations |
Summary
An expression is a tree of native operations that names its input columns and its output column. It is independent of any frame, so it behaves the same eagerly and lazily. In a lazy query, expressions are stored inside plan nodes. Because Polars can read them, it can ask which columns a step uses and where a step can move. The next chapters show how that information is used.
Exercise
You write q = pl.LazyFrame({"a": [1, 2], "b": [3, 4]}).select(pl.col("a") + pl.col("b"), pl.col("a") * 2). What is the problem, and how do you fix it without changing the values computed?
Show answer
Both expressions produce an output column named a (a binary operation takes the name of its left-most input), so Polars reports a duplicate-name error when the schema is resolved, even before collect(). Fix it with aliases: .select((pl.col("a") + pl.col("b")).alias("a_plus_b"), (pl.col("a") * 2).alias("a_double")).
Exercise
Why can Polars tell that (pl.col("temp") * 9 / 5 + 32) reads only the temp column, but not what pl.col("temp").map_elements(lambda v: v * 2, return_dtype=pl.Int64) does inside the lambda?
Show answer
The first is a tree of native operations that Polars can walk, and the only column reference in it is temp. The lambda is arbitrary Python code, so Polars can see only that it is called, not what it reads or computes. The optimiser must treat it as a black box.