Sub topic 10
Avoid hidden state and out-of-order execution
This chapter assumes you can start JupyterLab from a virtual environment, run cells, and use pandas to load a CSV file. It covers one problem: a notebook can show results that its saved code cannot reproduce.
What hidden state is
A notebook kernel is a running Python process. Every cell you run changes that process's memory. Variables, imports, and modified DataFrames stay there until you restart the kernel.
The notebook file stores only the cell text and the outputs from past runs. It does not store the kernel's memory. Hidden state is the gap between what the file shows and what the kernel holds. The file can show one thing while the kernel holds another.
The kernel remembers things the file no longer contains:
- A variable defined in a cell you later deleted.
- A value assigned in a cell you later edited.
- An import you removed from the top of the notebook.
- A DataFrame changed by a cell you ran three times.
How execution order causes bugs
Jupyter runs a cell when you tell it to, in any order. The number in brackets beside a cell, such as In [7], is the execution counter. It records the order in which cells actually ran. It does not record their order on the page.
If the counters run 1, 2, 3, 4 down the page, the notebook was run top to bottom. If you see 1, 5, 2, 9, cells ran out of order. The results may depend on a sequence that nobody can see in the file.
A worked example of the problem
Suppose a notebook has three cells in this order.
import pandas as pd
df = pd.read_csv("data/sales.csv")df = df[df["revenue"] > 0]print(len(df))Run them top to bottom and the third cell prints the number of rows with positive revenue. Now run the second cell again by itself. It filters a DataFrame that was already filtered. The result is the same here, because filtering twice on the same condition changes nothing. That is why the bug is easy to miss.
Change the second cell to something that is not idempotent, which means that running it twice gives a different result than running it once.
df["revenue"] = df["revenue"] * 1.1Each run of this cell raises revenue by another 10 percent. Run it three times by accident and the values are about 33 percent higher than intended. The notebook text shows a single 10 percent increase. The kernel holds a different number.
Common ways hidden state appears
| Cause | What happens | How to spot it |
|---|---|---|
| Re-running a cell that modifies data in place | Changes pile up on the same object | Counters show the same cell ran more than once |
| Deleting a cell that defined a variable | Later cells still work because the variable stays in memory | A fresh run raises `NameError` |
| Running cells out of order | A cell uses a value from a later cell's earlier run | Counters are not ascending |
| Removing an import | Code still works while the module is loaded | A fresh run raises `NameError` |
| Editing a cell without running it | The output shown belongs to the old code | The output does not match the code |
| Reading a file that changed on disk | The old data is still in memory | The numbers differ from a new run |
The standard fix: restart and run all
The main defense is to restart the kernel and run every cell from the top. This discards the memory and rebuilds it from the file alone. If the notebook still works and gives the same results, the file is a complete description of the analysis.
In JupyterLab, open the Kernel menu and choose Restart Kernel and Run All Cells…. Confirm the dialog. Other choices in the same menu differ:
- Restart Kernel… clears memory but runs nothing.
- Restart Kernel and Clear Outputs… clears memory and removes the saved outputs.
- Restart Kernel and Run up to Selected Cell… rebuilds only the state that earlier cells provide.
Do this before you share a notebook, commit it, or trust a result you plan to report.
Habits that reduce hidden state
Put imports and configuration at the top
Gather all imports and settings in the first cell. A reader then sees every dependency in one place. A missing import also shows up at once during a restart, instead of hiding behind a module that happened to be loaded.
import pandas as pd
import matplotlib.pyplot as plt
DATA_PATH = "data/sales.csv"Avoid changing a DataFrame in place across cells
Create a new name for each meaningful step. Then re-running a cell recomputes its result from an earlier, unchanged object.
raw = pd.read_csv("data/sales.csv")
positive = raw[raw["revenue"] > 0]
adjusted = positive.assign(revenue=positive["revenue"] * 1.1)Running the third line twice always gives the same adjusted, because it reads from positive, which it never modifies. The cost is more memory, since several versions of the data exist. For very large datasets, drop names you no longer need with del raw, and accept that this needs care.
Wrap repeated logic in functions
A function's local variables disappear when it returns, so they cannot leak into the kernel. Functions also make the analysis testable.
def clean_sales(frame):
"""Return a copy of the sales data with valid, adjusted revenue."""
out = frame[frame["revenue"] > 0].copy()
out["revenue"] = out["revenue"] * 1.1
return out
adjusted = clean_sales(raw)Calling clean_sales(raw) repeatedly never changes raw. Note the .copy() call. Without it, pandas may warn about setting values on a slice of another DataFrame.
Keep cells self-contained
A cell should say what it needs. If a cell depends on a variable, put it near the cell that defines it, and name things clearly. Avoid short names like x or tmp that get reused for unrelated values.
Move stable code out of the notebook
When a function is finished, move it into a .py module and import it. Combined with %autoreload 2 from the magic commands chapter, edits to the module take effect without a restart. This keeps the notebook for exploration and narrative, and puts tested code in files.
Detecting problems before they bite
Check the execution counters
Scan the numbers beside the cells. Gaps or jumps mean out-of-order runs. After a clean restart and run all, the counters read 1, 2, 3 and so on.
Check that a fresh run matches
You can verify programmatically. The nbconvert command re-runs every cell in a new kernel and saves the result.
jupyter nbconvert --to notebook --execute --output checked.ipynb analysis.ipynbThis writes checked.ipynb and leaves analysis.ipynb untouched. If a cell fails, the command stops with a traceback. That makes it a simple check for a stale variable or a missing import. Later chapters cover nbconvert in more detail.
Fail loudly on bad assumptions
Add short assertions that state what a cell expects. They turn silent wrong results into immediate errors.
assert raw["revenue"].notna().all(), "revenue has missing values"
assert (adjusted["revenue"] > 0).all(), "non-positive revenue remained"If hidden state corrupted adjusted, the second assertion can catch it.
Gotchas
- Restart and run all can fail on a notebook that "worked". That is the point. The failure shows the hidden state. Fix the notebook, not the check.
- Random results change between runs. If you sample or shuffle data, set a seed in the first cell, for example
rng = np.random.default_rng(42)after importing NumPy. Without a seed, a fresh run can differ for reasons that are not hidden state. - Slow cells tempt you to skip the restart. If loading takes minutes, save an intermediate file such as a Parquet or CSV copy and load that. Do not rely on memory as a cache.
- Stored outputs can mislead. A saved plot or table can come from code you have since changed. Treat outputs as untrusted until a fresh run produces them.
- Interrupting a cell can leave partial state. If you stop a cell halfway through a loop that modifies data, the object may be half updated. Restart rather than continue.
%autoreloadis not a substitute for restarting. It reloads modules, but it does not reset notebook variables that hold objects from the old module version.
Practice checklist
- Put all imports and constants in the first cell.
- Give each transformation step a new name, or wrap it in a function.
- Run Restart Kernel and Run All Cells… after each major change.
- Confirm the execution counters ascend from 1.
- Add assertions for the assumptions your analysis relies on.
Exercise
A notebook computes df["price"] = df["price"] * 2 in one cell. A colleague runs that cell four times while testing. Prices are now 16 times the original, but the file shows a single doubling. Name the problem and give two ways to prevent it.
Show answer
This is hidden state: the kernel's data was changed by repeated runs of a non-idempotent cell, so memory no longer matches what the file describes. First, restart the kernel and run all cells, which rebuilds the data from the original file. To prevent it, assign the result to a new name (for example df2 = df.assign(price=df["price"] * 2)) or wrap the step in a function that returns a new DataFrame, so re-running it always starts from the same unchanged input.
Exercise
You delete the cell that defined threshold = 100, but later cells that use threshold still run without error. Why, and how do you find out whether the notebook is still valid?
Show answer
The variable still exists in the kernel's memory, even though its defining cell is gone. Choose Kernel > Restart Kernel and Run All Cells. The fresh kernel has no threshold, so a cell that uses it raises NameError, which shows that the notebook file is incomplete.