Sub topic 2
Hidden State and Execution Order
This chapter assumes you can write Python in Jupyter, use the command line, and have installed packages with pip or conda. It covers how a notebook can hold state that its saved code does not explain, and how to spot and fix that.
What hidden state is
A notebook runs on a kernel, a live Python process. Each cell you run changes the kernel's memory: variables, imports, open files, and modified objects. The notebook file stores only the cell text and the outputs. It does not store the order you ran the cells in, or the memory they left behind.
Hidden state is anything in the kernel that affects a result but cannot be seen by reading the notebook from top to bottom. Two people with the same file can get different answers because their kernels hold different state.
How execution order causes drift
The execution counter beside each cell, such as [7], shows when it ran. Counters that are out of sequence, or that skip numbers, are a warning sign.
Consider these cells, in this order on the page:
# Cell 1
threshold = 10# Cell 2
kept = [x for x in range(20) if x > threshold]
print(len(kept))# Cell 3
threshold = 15Suppose you run cells 1, 2, 3, then edit cell 3 and rerun only cell 2. The output reflects threshold = 15, but a reader running top to bottom gets threshold = 10. The saved output no longer matches what the code produces.
Common sources
- Reassigned variables. A cell lower in the notebook changes a value that an earlier cell uses on the next run.
- Deleted cells. A variable defined in a cell you later removed still exists in memory, so code that depends on it keeps working until the kernel restarts.
- In-place mutation. Methods such as
df.drop(..., inplace=True)orlist.sort()change the object. Rerunning the cell applies the change a second time or to already-changed data. - Stale imports. After you edit an imported module, the kernel keeps the old version unless you restart or reload it.
- Session-only setup. Environment variables, working directory changes, and open connections made in one cell silently affect later ones.
A mutation example
This cell is safe to run once and wrong to run twice:
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 30.0]})
df["price"] = df["price"] * 1.1
print(df["price"].tolist())Because df is rebuilt in the same cell, this version is safe. Now split it into two cells, with the DataFrame created in one and the multiplication in another. Rerunning only the multiplication cell compounds the increase each time. The fix is to derive a new name instead of overwriting the old one:
df_adjusted = df.assign(price=df["price"] * 1.1)Rerunning this cell always produces the same result from df.
Habits that reduce hidden state
- Define each variable once, near where it is first needed.
- Prefer new names over in-place changes.
- Put imports and constants in the first cells.
- Keep cells small enough that each does one job.
- Treat an unexpected
NameErrorafter a restart as a useful finding, not a nuisance.
Exercise
Exercise
A notebook defines scale = 2 in cell 1 and uses it in cell 4. You delete cell 1 and keep working. Cell 4 still runs without error. Why is this a problem, and what happens when a colleague opens the notebook?
Show answer
The kernel still holds scale in memory from when cell 1 ran, so cell 4 works in your session. The saved file no longer defines it. A colleague running top to bottom in a fresh kernel gets a NameError in cell 4. Restarting your own kernel would have shown the problem first.
Exercise
A cell runs df.drop(columns=["id"], inplace=True). Running it a second time raises a KeyError. Rewrite it so it can be rerun safely.
Show answer
Assign to a new name instead of changing the original: df_clean = df.drop(columns=["id"]). Because df is never changed, rerunning the cell gives the same result each time.