Sub topic 10
Avoid hidden state and out-of-order execution
This chapter assumes you can run cells in JupyterLab, have a project kernel registered, and can load a DataFrame with pandas. It explains why a notebook can show results that its own code cannot reproduce, and how to prevent that.
What hidden state is
A notebook kernel is one running Python process. Every cell you execute changes that process's memory. The notebook file stores the code and the saved outputs, but it does not store the memory. If the memory contains values that no visible cell in the current order would create, you have hidden state.
Cells can run in any order, and the number in the margin ([3], [7]) records the order in which they actually ran. Nothing forces that order to match the order on the page.
How it goes wrong
Consider three cells in this order on the page:
import pandas as pd
df = pd.read_csv("data/sales.csv")df = df[df["revenue"] > 0]print(len(df))Suppose you run the second cell three times while experimenting. Each run reassigns df to a filtered copy of the previous df. For this particular filter, the result is the same each time, but with a filter like df["revenue"] / 2 > 100 or a step like df["revenue"] = df["revenue"] * 1.1, each re-run changes the data again. The printed count then reflects an execution history that no one can see on the page.
Two other common causes:
- You delete a cell that defined a variable. The variable stays in memory, and later cells keep working until you restart.
- You rename a column in a cell, run it once, then edit it to do something else. Later cells still depend on the old rename.
Detect it
Use these signs as warnings:
- Execution numbers in the margin are not increasing from top to bottom.
- A cell uses a name that is not defined or imported anywhere above it.
- Results change when you re-run the same cell without editing it.
- A colleague gets a
NameErroror different numbers from your file.
You can also inspect the kernel directly with the %who magic command, which lists the variables currently defined. Compare that list to what the visible cells should have created.
Fix it: restart and run all
The reliable test is to discard the memory and run everything in order. In JupyterLab, open the Kernel menu and choose Restart Kernel and Run All Cells. The kernel process starts empty, then every cell runs from top to bottom.
If a cell fails, the notebook had hidden state. Fix the cell that raised the error, so that it creates what it needs, then restart and run all again. Repeat until the whole notebook finishes cleanly.
Habits that prevent it
- Put all imports and file paths in the first cell.
- Load the raw data in one cell, and derive new DataFrames in later cells instead of overwriting the original. For example, write
clean = df[df["revenue"] > 0]rather thandf = df[...]. Re-running a cell then gives the same result. - Avoid cells that modify a variable in place (
df["revenue"] *= 1.1) unless they also build that variable from scratch. - Restart and run all before you save, share, or commit.
- Move reusable logic into functions or a
.pymodule, which%autoreloadcan refresh without a restart.
Exercises
Exercise
A notebook shows execution numbers [1], [2], [5], [3] from top to bottom, and the last cell prints a correct-looking result. A colleague opens it and gets a NameError. What is the most likely cause, and what is the first step to fix it?
Show answer
A variable was defined in a cell that ran out of order, was deleted, or was renamed, so it exists only in your kernel memory. The first step is to choose Restart Kernel and Run All Cells, find the cell that raises the NameError, and change the notebook so that the name is defined above the cell that uses it.
Exercise
Why is clean = df[df["revenue"] > 0] safer than df = df[df["revenue"] > 0] in a cell you might run several times?
Show answer
The first form always builds clean from the same unchanged df, so each run gives the same result. The second form reassigns df each time, so every re-run filters already-modified data, and the outcome depends on how many times you ran the cell.