Skip to the solution
MediumDSA11 min read

How does Polars LazyFrame query optimization work?

1.1k views

The problem

Question presented to candidate: "In Polars, if I write pl.scan_parquet(path).filter(...).select(...).head(10).collect(), what actually happens between building that chain and getting a DataFrame back? Which optimizations does Polars apply, and how would you check that they happened?"

What a strong answer should cover:

  • A LazyFrame holds a logical query plan, not data; methods add nodes; .collect() optimizes the plan and then executes it (scan_* functions start a lazy plan from a file)
  • Predicate pushdown (filters applied as early as possible, at the scan), projection pushdown (only needed columns are read), slice pushdown (only the needed rows)
  • Expression and plan rewrites: expression simplification / constant folding, common subplan elimination (cache repeated subtrees, for example in self-joins), plus type coercion, join ordering and cardinality estimation listed in the Polars user guide
  • How to inspect: lf.explain() (optimized plan) vs lf.explain(optimized=False); read PROJECT n/m COLUMNS and SELECTION on the scan line
  • What defeats it: Python UDFs (map_elements) the optimizer cannot see into, reading eagerly with read_csv before going lazy, collecting in the middle of a pipeline

Code / implementation expected: Optional β€” a lazy query and its explain() output, or a sketch of how a filter moves below a projection into the scan.

  • polars
  • lazy
  • performance

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonA toy lazy engine: predicate, projection and slice pushdown with before and after plans
PythonExpression rewrites: constant folding, common subexpressions, and why a Python UDF blocks pushdown

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 46 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does collections.deque work internally?

Continue