Sub topic 13
Restart and Run All: Removing Hidden State
This chapter assumes you can run cells in Jupyter, write basic pandas code, and have followed the earlier chapters on setup, loading, and cleaning. It covers why a notebook can look correct and still fail on a fresh run, and how to check for that.
Why notebooks hide state
A notebook kernel is a running Python process. Each cell you execute changes that process: it creates variables, redefines functions, and modifies objects. The notebook file stores your code and the saved outputs. It does not store the order in which you ran things, and the outputs on screen may come from code that no longer exists.
This is hidden state: values in the kernel that the visible cells do not explain. A reader who opens the file sees the cells top to bottom. The kernel may have reached its current condition in a different order. The two can disagree without any warning.
The number in the left margin of each code cell, such as In [17], shows the execution order. If the numbers are not increasing from top to bottom, the notebook was run out of order.
How hidden state appears
The following situations cause most problems in an EDA notebook.
| Cause | What happens | How it shows up later |
|---|---|---|
| Deleted cell | A cell that defined a variable is removed, but the variable stays in memory. | A later cell works now and raises `NameError` on a fresh run. |
| Out-of-order execution | A cell near the end is run before one near the top. | The notebook gives different results from top to bottom. |
| Edited but not re-run cell | A cleaning rule is changed, but downstream cells keep old outputs. | Plots and tables describe data the code no longer produces. |
| In-place mutation | A cell changes a DataFrame directly. | Running the cell twice gives a different result than running it once. |
| Redefined name | `df` is reassigned in several places. | A reader cannot tell which version of `df` a plot uses. |
| Stale import or function | You edit a function but the kernel still holds the old version. | Behavior differs between your session and a colleague's. |
A concrete failure
Suppose an early exploration cell adds a column to the cleaned data:
import pandas as pd
df = pd.DataFrame({"amount": [10.0, 20.0, 400.0], "region": ["north", "south", "north"]})
df["amount_log"] = df["amount"].apply(lambda x: x ** 0.5)You later decide the column is not useful and delete that cell. Two cells below, a plot still uses it:
df["amount_log"].plot.hist()The plot keeps working because df in the kernel still has the column. In a fresh kernel, the first cell is gone, and the plot cell raises KeyError: 'amount_log'. Nothing on screen warned you. The notebook was broken from the moment you deleted the cell.
Mutation causes a second kind of failure. Compare these two cells:
import pandas as pd
df = pd.DataFrame({"amount": [10.0, 20.0, 30.0]})
# Not safe to re-run: each run doubles the values again.
df["amount"] = df["amount"] * 2
print(df["amount"].tolist())Run this cell once and you get [20.0, 40.0, 60.0]. Run it again in the same kernel and df is created fresh, so it is safe here. The danger appears when the pd.DataFrame(...) line sits in an earlier cell. Then each re-run of the second cell doubles the values again. A cell that depends on its own previous output is not idempotent, meaning that running it twice gives a different result than running it once.
The fix is to derive new objects from stable inputs:
import pandas as pd
df_raw = pd.DataFrame({"amount": [10.0, 20.0, 30.0]})
def add_scaled(df, factor):
out = df.copy()
out["amount_scaled"] = out["amount"] * factor
return out
df = add_scaled(df_raw, 2)
print(df["amount_scaled"].tolist())Because df is rebuilt from df_raw every time, running the cell once or ten times gives [20.0, 40.0, 60.0]. This is the same pattern as clean_orders from the cleaning chapter: a function takes a DataFrame and returns a new one.
The check: restart and run all
The test for hidden state is direct. Throw away the kernel and run every cell in order from a clean process.
- In the Jupyter menu, choose Kernel, then Restart Kernel and Run All Cells. In JupyterLab the wording is similar. In VS Code, use Restart and then Run All.
- Watch for the first cell that raises an error. Cells after it do not run, so the first error is the one to fix.
- Fix the cause, then restart and run all again.
- Repeat until the whole notebook runs with no errors.
- Compare the final outputs with what you expected. A run with no errors can still produce different numbers.
Run this check at regular points, not only at the end. A good rhythm is after finishing each major section, and always before sharing the notebook or committing it to version control. The longer you wait, the more problems pile up and the harder it is to tell which edit caused each one.
Checking from the command line
The menu check relies on you watching the screen. For a repeatable check, you can execute the notebook from the command line with nbconvert. This runs all cells in a new kernel and stops at the first error.
jupyter nbconvert --to notebook --execute eda_orders.ipynb --output eda_orders_checked.ipynbIf the command exits with a non-zero status, a cell failed. This makes it possible to run the check in a script or in continuous integration. The command writes to a separate output file, so your working notebook is not overwritten.
Habits that prevent hidden state
These practices reduce how often the check fails.
- Keep raw data untouched. Load into
df_rawonce and never modify it. Every later DataFrame is derived from it. - Use functions that return new objects. Avoid
inplace=Trueand direct assignment to shared DataFrames in exploration cells. Call.copy()before adding columns. - Give each stage a distinct name.
df_raw,dffor the cleaned data, and names likedf_northfor subsets. Avoid reassigningdfto different things. - Put all imports and constants in the setup cell. If a cell near the end imports a library, a reader running a subset of cells can hit an error. Setup belongs at the top.
- Avoid depending on variables from deleted cells. When you delete a cell, restart and run all right away.
- Seed random operations. Sampling and shuffling should use the
rngobject from the setup cell, so reruns give the same sample. - Keep cell order meaningful. If a cell needs a result from below it, move it. The notebook should read in the order it runs.
Edge cases
Cells that are slow or have side effects
Some cells query a database, download a file, or write to disk. Running everything again repeats those actions. Guard them. For example, download only if the file is absent:
from pathlib import Path
RAW_PATH = Path("data/raw/orders.csv")
if not RAW_PATH.exists():
raise FileNotFoundError(
f"{RAW_PATH} is missing. Place the raw export there before running."
)Failing with a clear message is better than a notebook that silently uses whatever is in memory.
Results that change between runs
If a restart changes your numbers, look for unseeded randomness, a data file that changed on disk, or a dependency that behaves differently. Print library versions in the setup cell so you can compare environments:
import sys
import pandas as pd
print("python", sys.version.split()[0])
print("pandas", pd.__version__)Saved outputs that no longer match
A notebook saved after an out-of-order session can contain outputs from different code versions. After a successful restart and run all, save the notebook. The stored outputs then match the stored code.
Interactive widgets and manual inputs
Cells that depend on a slider position or a hand-typed value are hard to reproduce. Move such values into named constants in the setup cell, so the run is fully described by the file.
Reading a notebook you did not write
When you receive someone else's notebook, do not trust the outputs on screen. Restart and run all first. If it fails, you have learned that the notebook is not reproducible, and you can tell the author the exact cell where it breaks. If it passes, compare your results with the saved ones. Any difference is a lead to investigate before you build on the analysis.
Summary of the working model
The kernel is one more input to your analysis, and it is the one a reader cannot see. Restart and run all removes it from the equation: if the notebook produces the same results from a blank kernel, the file alone describes the analysis. Make this check a habit at section boundaries and before every handoff.
Exercise
A colleague's notebook has a plot cell that uses df["revenue_per_item"]. The cell that created this column was deleted last week. The plot still renders on their machine. Explain why, say what you would see after "Restart Kernel and Run All Cells", and describe how to fix the notebook.
Show answer
The kernel on their machine still holds a df that has the revenue_per_item column from the deleted cell, so the plot works from memory. After a restart, df is rebuilt only from the visible cells, so the column does not exist and the plot cell raises KeyError: 'revenue_per_item'. To fix it, either restore the column creation in a cell placed before the plot, preferably inside a function that returns a new DataFrame such as add_revenue_per_item(df), or remove the plot if the column is no longer needed. Then restart and run all again to confirm that every cell passes.
Exercise
This cell sits below a cell that defines df = clean_orders(df_raw). Why is it unsafe to re-run, and how would you rewrite it?
df["amount"] = df["amount"] * 1.1
Show answer
Each run multiplies the already-updated column by 1.1 again, so the result depends on how many times the cell was run. This is a mutation of shared state. Rewrite it to derive a new column or a new DataFrame from a stable input, for example df_priced = df.assign(amount_with_tax=df["amount"] * 1.1). Running this cell repeatedly gives the same result because df["amount"] is never changed.
Exercise
You run jupyter nbconvert --to notebook --execute eda_orders.ipynb and it stops with an error in cell 12, but cells 13 to 20 are also broken in your editor. Which cell should you fix first, and why?
Show answer
Fix cell 12 first. Execution stops at the first error, so later cells never ran in the check. Their problems may be separate, or they may be caused by cell 12 failing to define something they need. After fixing cell 12, run the check again and fix the next failure it reports.