Sub topic 2
Hidden state and execution order
This chapter assumes you can run Jupyter notebooks, write basic Python, and use the command line. It covers the main reason a notebook gives different answers on different days: state that exists in the running kernel but is not visible in the saved file.
What hidden state is
A notebook has two parts. The file on disk holds cells, their text, and saved outputs. The kernel is a separate running Python process that holds every variable, import, and open file you have created so far. When you run a cell, the kernel changes. When you edit or delete a cell, the kernel does not change back.
Hidden state is anything in the kernel that the saved cells no longer explain. A reader who opens the file sees the cells. They cannot see what the kernel remembers.
The execution counter in the left margin, such as In [7], shows the order in which cells actually ran. That order often differs from the order on the page.
How hidden state appears
Four patterns cause most problems.
- Out-of-order execution. You run a cell lower in the notebook before one above it. The result depends on a sequence that nobody wrote down.
- Deleted cells. You define
threshold = 0.5in a cell, use it, then delete the cell. The variable stays in memory, and later cells keep working until the kernel restarts. - Re-run cells that modify data. A cell that changes a variable in place gives a different result each time you run it.
- Stale imports and modules. You edit a helper module, but the kernel still holds the old version it imported earlier.
An example of drift
Consider these three cells, saved in this order.
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 30.0]})df["price"] = df["price"] * 1.1print(df["price"].mean())Run top to bottom once, and the mean is 22.0. Now run the second cell a second time by accident. Prices are multiplied by 1.1 again, and the mean becomes 24.2. The saved output of the third cell shows whichever value was current at the time. Nothing in the file tells a reader how many times the second cell ran.
The fix for this specific case is to avoid changing a variable in place. Write each step so that running it again gives the same result.
import pandas as pd
raw = pd.DataFrame({"price": [10.0, 20.0, 30.0]})
adjusted = raw.assign(price=raw["price"] * 1.1)
print(adjusted["price"].mean())Here raw is never modified. You can run the second and third lines as often as you like and always get 22.0, apart from floating-point rounding in the last digits.
A diagram of the problem
The diagram shows how the kernel and the saved file can disagree.
Detecting hidden state
You do not need special tools for a first check. Look for these signs.
- Execution counters that are not in increasing order down the page.
- Gaps in the counters, which mean cells were skipped or deleted.
- A cell that uses a name you cannot find defined anywhere above it.
- Outputs that do not match what the code above them would produce.
The reliable test is to restart the kernel and run every cell in order. The next chapter treats this as a routine check, so here we only note why it works: a restart throws away everything the kernel remembers, so only the file can supply state.
You can also list what the kernel currently holds. In a notebook cell, the %whos magic prints every user-defined variable with its type.
%whosCompare that list with the names your cells define. A variable in the list that no cell creates is a leftover.
Common sources of hidden state
Mutable objects and in-place changes
Methods such as list.append, df.drop(..., inplace=True), and df.sort_values(..., inplace=True) change an object. Re-running the cell changes it again. Prefer operations that return a new object and assign it to a new name.
Global configuration
Libraries often keep settings in module-level state. A call such as pd.set_option("display.precision", 2) affects every later cell, and it persists even after you delete the cell that set it. Put such calls in one cell near the top so they appear in the file.
Unseeded random numbers
If a cell draws random numbers without a fixed seed, each run gives different values. This is not strictly hidden state, but it looks similar: the same saved code gives different outputs. A later chapter covers seeding in detail.
Files read and written during the run
A cell that reads data/clean.csv depends on whatever file is on disk at that moment. If another cell, or another program, rewrites that file, the result changes with no change to the code.
Interactive input
Values typed into input(), widgets, or pasted into a cell by hand are not in the file unless you save them there.
Stale imports
Python caches imported modules. If you change helpers.py and re-run import helpers, nothing happens because the module is already loaded. In an interactive session you can ask IPython to reload changed modules automatically.
%load_ext autoreload
%autoreload 2This is a convenience for development. It does not remove the need for a full restart before you trust a result, because autoreload cannot always repair objects created from older versions of a class.
Writing cells that are safe to re-run
A cell is idempotent if running it twice gives the same state as running it once. Idempotent cells make out-of-order execution much less harmful. Some habits help.
- Build new names from old ones instead of overwriting:
clean = raw.dropna(), notraw = raw.dropna(). - Put all imports and configuration in the first cell.
- Define a value in the same cell that uses it, or in a cell clearly above.
- Avoid cells that append to a list or accumulate a total across runs.
- Keep a cell short enough that its inputs and outputs are clear.
The table summarizes the contrast.
| Pattern that hides state | Safer alternative |
|---|---|
| `df = df.dropna()` in a middle cell | `clean = df.dropna()` |
| `results.append(x)` in a loop cell | `results = [f(x) for x in xs]` |
| Setting options in a late cell | Setting options in the first cell |
| Deleting the cell that defines a variable | Restarting and re-running after any deletion |
| Typing a value into a widget | Writing the value as a named constant in a cell |
Edge cases
- Restart does not clear disk state. A restarted kernel still reads files written by earlier runs. If a cell writes
cache.parquetand a later run reads it, a stale cache can survive a restart. Delete or version caches deliberately. - Environment variables persist. Values set with
os.environlast only for the kernel process, but ones set in the shell that launched Jupyter come back after every restart. These are outside the file as well. - Background threads and open connections. A database connection or running thread started in one cell lives on until the kernel stops.
- Cell magics with side effects.
%cdchanges the working directory for every later cell. Relative paths then point somewhere else, so re-running from the top can fail if the directory was already changed. - Interrupted cells. If you stop a cell halfway, variables it assigned before the interruption keep their new values, while later ones keep old values. The state is a mix of both.
Reading someone else's notebook
When you receive a notebook with saved outputs, treat the outputs as claims, not facts. They show what one particular session produced. Check the execution counters first. If they run 1, 2, 3, and so on without gaps, the notebook was probably run cleanly once. If they jump around, plan to restart and re-run before you rely on any number in it.
Summary of habits
- Write cells that can be run more than once without changing the result.
- Avoid in-place modification of shared objects.
- Keep imports, options, and constants in one early cell.
- Watch the execution counters for gaps and reordering.
- After deleting or reordering cells, restart the kernel before trusting any output.
Exercise
A notebook has three cells in this order: (1) import pandas as pd, (2) df = pd.read_csv("data.csv"), (3) df = df[df["score"] > 50]. You run cell 3 twice, then change its threshold to 60 and run it once more. The counters read 1, 2, 5. Why might the final df be misleading, and how would you change cell 3 so that re-running it is safe?
Show answer
Each run of cell 3 overwrites df with a filtered copy of the previous df. The first two runs kept rows above 50. The third run then filtered that already-reduced data with the threshold of 60, so the result happens to match filtering the original once, but only by chance. If the order of thresholds had been reversed (60, then 50), rows would have been lost for good. The gap in the counters (3 and 4 are missing) shows that cells were run more than once. To make it safe, keep the loaded data in df and write filtered = df[df["score"] > 60]. Then cell 3 reads df and never changes it, so every run gives the same result.
Exercise
You delete a cell that defined LIMIT = 100, but later cells that use LIMIT still run without errors. What is happening, and what single action reveals the problem?
Show answer
The kernel still holds the variable LIMIT from when the deleted cell ran, so later cells find it in memory. The file no longer defines it. Restarting the kernel and running all cells from the top discards the variable, and the first cell that uses LIMIT then raises a NameError.