Sub topic 4
Lazy evaluation and task graphs
This chapter assumes you know basic Python and pandas (selecting, filtering, assign, groupby). It also assumes you have met Dask partitions from the earlier chapters. Here you will learn what Dask does when you write a pandas-style line, and why most lines return almost instantly.
What "lazy" means in Dask
In pandas, each line runs immediately. df[df["fare"] > 15] scans the data and returns a new DataFrame. In Dask, the same line only records what you asked for. Nothing is read or calculated. The result is a Dask object that remembers a plan.
This design has three reasons:
- The data may not fit in memory, so Dask cannot load it just to answer one line.
- Dask can see the whole plan before it runs anything. It can then skip work, drop unused columns, and run independent pieces in parallel.
- Planning is cheap. Building a plan for terabytes of data takes milliseconds.
Here is a small example.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b"],
"fare": [10.0, 20.0, 30.0, 40.0],
})
ddf = dd.from_pandas(pdf, npartitions=2)
mean_fare = ddf[ddf["fare"] > 15].groupby("zone")["fare"].mean()
print(type(mean_fare)) # a lazy Dask object, nothing computed yet
print(mean_fare) # shows structure (name, dtype), not valuesPrinting mean_fare shows its type, name, and the number of partitions. It does not show the numbers you would see in pandas. To get values, you must ask for them with .compute(), which the next chapter covers.
The task graph
A task graph is the plan Dask builds. It is a directed graph. Each node is a task: one Python function call on specific inputs. Each edge says that one task's output feeds another task.
Take the filter and groupby above on a frame with two partitions. The graph has roughly this shape:
The diagram below shows it in a form the platform can draw.
Three things are worth noticing:
- Per-partition work is independent. The two branches on the left do not depend on each other, so a scheduler can run them at the same time.
- Aggregations are split in two stages. Each partition produces a small partial result (sum and count). A later task combines them. A mean cannot be computed by averaging partition means, because partitions can have different sizes, so Dask carries sums and counts instead.
- The graph is data about your computation. It is a plain Python structure, so Dask can inspect, optimize, and visualize it before running.
What a Dask object holds
A Dask DataFrame or Series has two parts:
- The graph: the tasks needed to produce each of its partitions.
- Metadata: the column names, dtypes, and index type, plus the partition count. Dask keeps an empty pandas object that describes the output, called
meta. A later chapter covers it in detail.
Metadata is why print(ddf) can show column names and dtypes without reading any rows. It is also why some mistakes surface early. If you select a column that does not exist, Dask raises a KeyError at the line where you wrote it, not later at compute time.
You can check this yourself:
print(ddf.npartitions) # 2
print(ddf.dtypes) # known without computing
print(mean_fare.npartitions)dtypes and npartitions are answered from metadata. Anything that needs real values, such as the number of rows, requires running the graph.
Inspecting the graph
Dask gives you tools to look at the plan. The simplest is visualize(), which draws the graph with Graphviz. It needs the graphviz Python package and the Graphviz system program.
mean_fare.visualize(filename="mean_fare_graph.png")Without Graphviz installed, you can still count tasks. Every Dask collection exposes its graph as a mapping through __dask_graph__().
graph = mean_fare.__dask_graph__()
print(len(graph)) # number of tasks or layers
print(type(graph).__name__)Recent Dask versions store the graph as layers, a group of similar tasks such as "filter every partition". The exact count and the type name depend on the Dask version, so treat these outputs as a rough view, not a stable interface. For a small example, visualize() is the most readable check. For a large one, the graph can contain thousands of tasks, and drawing it is not practical.
Lazy evaluation and the pandas habits it breaks
Because nothing runs until you ask, some pandas habits behave differently.
Printing is not computing
In pandas, printing shows data. In Dask, it shows structure. Use ddf.head() to look at real rows. head() is a special case. It computes only the first partition by default, so it is fast, but it can mislead you. If the first partition is not representative (sorted data, for example), head() will not show what the rest looks like.
Errors can appear late
Metadata catches many errors early, but not those that depend on values. Suppose a function fails on one malformed row in partition 37. Building the graph succeeds. The error appears only when that partition's task runs, and the traceback comes from inside the scheduler.
Reusing a lazy object repeats the work
Each .compute() call runs the whole graph needed for that result. Look at this pattern:
filtered = ddf[ddf["fare"] > 15]
total = filtered["fare"].sum()
count = filtered["fare"].count()
print(total.compute()) # reads and filters the data
print(count.compute()) # reads and filters the data againThe second call does not reuse the first call's filtered data. Both read the source and filter it. For cheap in-memory data this is harmless. For a large Parquet dataset it doubles the cost. Two fixes exist:
- Compute both results together with
dask.compute(total, count). Dask merges the two graphs and runs the shared tasks once. - Call
persist()on the shared intermediate to keep its partitions in memory.
import dask
total_value, count_value = dask.compute(total, count)
print(total_value, count_value)The next chapter covers compute and persist in full.
Graph size has a cost
Planning is cheap, but not free. Every partition adds tasks to every step. A DataFrame with 100,000 tiny partitions and ten operations produces about a million tasks. The scheduler spends time tracking them, and the overhead can exceed the work itself. This is one reason partition sizing matters, and a later chapter returns to it.
Optimization before execution
When you compute, Dask first optimizes the graph. The main optimizations are:
- Column projection. If you read Parquet and use only two columns, Dask can read only those two columns from disk.
- Fusion. Chains of simple steps on one partition (filter, then assign, then select) can be merged into one task. This cuts scheduler overhead and avoids storing intermediate results.
- Shared work. Identical tasks that appear in several branches run once.
You do not turn these on. They run automatically, and the exact set depends on your Dask version and on whether you use the newer query-planning DataFrame implementation. The practical result is that the order and style of your pandas code matter less than you might expect, but writing selective code still helps: select the columns you need early.
A mental checklist
When you write Dask code, ask these questions about each line:
| Question | Typical answer |
|---|---|
| Does this line run any computation? | Usually no. It adds to the graph. |
| What do I get back? | A Dask object with metadata and a plan. |
| When will an error show up? | Metadata errors now. Value-dependent errors at compute time. |
| Will I use this result more than once? | If yes, compute together or persist. |
| How many tasks does this create? | Roughly partitions times steps. |
Common mistakes
- Using a Dask object where Python needs a real value. Code such as
if ddf["fare"].sum() > 100:fails or behaves oddly, because the sum is a lazy object, not a number. Call.compute()first. - Calling
.compute()too early. Computing in the middle of a pipeline pulls data into one pandas object in your process. If the result is large, you lose the point of using Dask. Compute at the end, after filtering and aggregating, when the result is small. - Calling
.compute()in a loop. Each call runs a full graph. Build a list of lazy results and pass them todask.compute(*results)once. - Assuming a quick line means a cheap line. A line like
ddf.sort_values("fare")returns instantly. It only records an expensive shuffle that runs later.
Summary
Dask evaluates lazily. Each pandas-style operation adds tasks to a graph and returns a new Dask object carrying that graph and its metadata. The graph splits work into independent per-partition tasks plus small combine steps, which lets a scheduler run work in parallel. Dask optimizes the graph before it runs. Because nothing executes until you ask, you must plan for repeated work, late errors, and the cost hidden behind fast-looking lines.
Exercise
You run a = ddf[ddf["fare"] > 15], then s = a["fare"].sum().compute() and c = a["fare"].count().compute() on a large Parquet dataset. The job takes about twice as long as you expected. Why, and how would you fix it? Give two options.
Show answer
Each .compute() call runs the full graph from the source, so the data is read and filtered twice. Option 1: build both results lazily and run them together with dask.compute(a["fare"].sum(), a["fare"].count()), so Dask merges the graphs and runs the shared read and filter once. Option 2: call a = a.persist() first so the filtered partitions stay in memory, then compute both results from the persisted data.
Exercise
A colleague says that ddf["missing_column"] will fail only when .compute() is called. Is that correct? Explain what Dask uses to decide.
Show answer
No. Dask keeps metadata (column names and dtypes) for every collection, so selecting a column that does not exist raises a KeyError immediately, at graph-building time. Only errors that depend on actual values, such as a function failing on a malformed row in one partition, wait until compute time.