Jupyter as a lab: kernels, hidden state and magics
Jupyter architecture (interface, server, kernel, and message protocol), registering the project environment as a kernel, and working without the hidden state that makes so many notebooks irreproducible. IPython magics for timing, profiling, and debugging; autoreload for module development; and a workflow separating exploration from reliable code.
After this lesson you can
- Describe Jupyter architecture and what happens, message by message, when a cell runs.
- Register a uv environment as a kernel with ipykernel and check which interpreter runs each cell.
- Detect and avoid hidden-state dependencies caused by out-of-order execution.
- Use %timeit, %prun, %debug, and %autoreload in daily work.
- Decide which code belongs in a notebook and which in the importable package.
Before you start
Motivation: the notebook that worked yesterday
You open the notebook that gave you a good result yesterday. Cells are in place and so are outputs: the metrics table, loss-curve figure, and number intended for the report. You restart the kernel, press “run all,” and the fourth cell fails with a NameError. Or worse, nothing fails and the final number differs.
This is not bad luck. In 2019 Pimentel, Murta, Braganholo, and Freire downloaded nearly 1.4 million public GitHub notebooks and reran them: about one in four reached the end without errors, and only around 4% reproduced the same saved results. Identified causes include missing dependencies and, just behind them, hidden state and out-of-order execution: notebooks whose outputs were produced in an execution order the document does not record.
The root of the problem is that a notebook is two different things that look like one:
- The document: a list of cells with their text and last saved outputs. This is what you read and upload to git.
- The process: a live Python interpreter, the kernel, with all variables created by any cell you have run, in execution order, including cells you have deleted or changed.
As you work, the second gradually diverges from the first and nothing on screen warns you. This lesson explains the machinery beneath so that does not happen: processes and messages, how to identify the interpreter running cells, a precise model of reproducible output, IPython tools for timing, profiling, and debugging, and a workflow where notebooks explore and reliable code lives in a package. Start by seeing the problem yourself.
What you should have seen:
- The counter gap reveals the trap. Cell 3 shows
[4]and cell 2[2]: someone ran something numbered 3 that is no longer visible. It was cell 3 itself, run twice. Sincex = [v / escala for v in x]reads and rewritesx, each execution divides again, and the visible mean1.25is not the text’s2.5. - A cell can be correct while its output is not. Cell 6 faithfully prints the value of
mediain memory. The error is upstream and propagates to everything depending on it. - Editing without running immediately creates hidden state. Change cell 2 to
escala = 4: the text says 4 while the kernel still has 2. - Deleting a cell does not delete its variables. Delete cell 2 after running it and everything still works until restart. Then cell 3 fails with
NameError, and “run all” stops there. - Restarting the kernel does not clear outputs. After “Restart kernel” memory is empty, but old outputs and counters remain on screen.
Architecture: who runs your code
Jupyter is not one program but an architecture of processes communicating by messages. Separating interface from execution lets the same notebook work in a browser, VS Code, or a remote GPU server, with Python, Julia, or R kernels.
A message is a JSON dictionary with five parts: header (unique identifier msg_id, type msg_type, session, date, and protocol version), parent_header (header of the message being answered), metadata, content (type-specific contents), and buffers (optional binary data). Between server and kernel it is also HMAC-signed with a key the kernel reads at startup from its connection file: JSON with the five ports, IP address, and key. The five channels have distinct roles:
| Channel | ZeroMQ pattern | Purpose |
|---|---|---|
| shell | request and reply | execute_request, completion, inspection, kernel information; the reply goes only to the requester |
| IOPub | publish and subscribe | everything execution produces (stream, display_data, execute_result, error, status), broadcast to all clients |
| stdin | request and reply, initiated by the kernel | input() and getpass(): the kernel asks the requesting client |
| control | request and reply | shut down, restart, interrupt (on supporting kernels), or debug; it has its own queue so it is not stuck behind code |
| heartbeat | echo | periodic heartbeat indicating whether the kernel process is alive |
The next figure follows what happens when you press Shift+Enter, message by message. The messages are real: captured with jupyter_client against ipykernel 7, and you will reproduce them in the local laboratory.
The animation explains several behaviors that can seem mysterious in daily work:
- The
[n]counter belongs to the process, not the document. The kernel assigns it when execution starts (execute_input) and it only increases. A gap is information: there were executions you no longer see. - Output arrives in chunks.
ipykerneldoes not send one message for eachprint: it accumulates stdout and flushes at most every 0.2 seconds. Progress bars and training logs appear in bursts for that reason, not because your loop is jerky. - A busy kernel does not freeze the interface. They are separate processes: you can scroll, edit, and save while the kernel works. You cannot execute something else simultaneously because the kernel handles shell requests one at a time on one thread; the second cell waits in the queue with
[*]. - Interrupt bypasses the queue. It enters through the server REST API, which signals the process (or sends a control-channel message). In Python it becomes a
KeyboardInterruptraised at the next bytecode instruction; if the thread is in a long C-extension operation, handling may be delayed and restart may be necessary. - After an error, queued work is discarded. JupyterLab requests carry
stop_on_error, and the kernel answers everything queued withstatus: "aborted"without running it. This stops “run all” at the first failing cell. - A figure is a bundle of representations.
display_datacarries the same object in several MIME types (PNG, text, sometimes HTML or SVG), and the client picks the richest it can render.DataFrameHTML tables and interactive widgets work similarly.
The kernel lifecycle
A kernel is created when you open the notebook (or choose one in the selector), lives while the notebook is open, and dies when closed or shut down. Four operations the client can request have very different effects on state:
| Operation | What it does | Python state | On-screen outputs | Counter |
|---|---|---|---|---|
| Interrupt | signal the process | retained | retained | continues |
| Restart | kill the process and start another | lost | retained | returns to 1 |
| Restart and run all | restart and send all cells in order | rebuilt from text | replaced | 1, 2, 3… |
| Shut down | kill the process | lost | retained |
The penultimate row is the only operation reliably connecting document and state: the others retain on-screen outputs the current kernel did not produce.
Your project’s kernel
In the previous lesson you created the project’s virtual environment with uv, dependencies pinned in the lockfile, and the project itself declared as an installable package. Now ensure cells run in that environment rather than any other Python on the machine.
The server knows which kernels exist through kernel specifications (kernelspecs): folders with a kernel.json file whose argv field is literally the command launching the process. Registering the project environment as a kernel means writing one such folder:
uv add --dev ipykernel # ipykernel en el entorno del proyecto, como dependencia de desarrollo
uv run python -m ipykernel install --user --name atlas --display-name "Python (atlas)"
uv run --with jupyterlab jupyter lab # o tu JupyterLab de siempre: el kernel aparece en el selector
The second command creates kernels/atlas/kernel.json in the user’s Jupyter data folder (%APPDATA%\jupyter on Windows, ~/.local/share/jupyter on Linux). With ipykernel 7, its contents are essentially:
{
"argv": ["C:\\Users\\...\\proyecto\\.venv\\Scripts\\python.exe",
"-m", "ipykernel_launcher", "-f", "{connection_file}"],
"display_name": "Python (atlas)",
"language": "python",
"metadata": {"debugger": true},
"kernel_protocol_version": "5.5"
}
The important part is the absolute executable path in argv: that kernel uses the .venv Python regardless of who launches it. jupyter kernelspec list shows registered kernels and their locations; if you move or recreate the environment, register it again. VS Code skips this step: its kernel selector directly offers interpreters it finds, including the project .venv.
The check that should open any serious project notebook is to ask the kernel itself who it is:
import sys
print(sys.executable) # ruta del intérprete que ejecuta ESTA celda
print(sys.prefix) # raíz del entorno: debe ser el .venv del proyecto
Hidden state: the text is not the program
The initial interactive suggests a precise question: when can I trust an output on screen? Answering requires a model of what a notebook does.
To reason about particular cells, each cell has a set of reads , names it uses before assigning them within the cell, and writes , names it assigns. For x = [v / escala for v in x], and . In clean execution, the value of read by cell is what the last previous cell writing wrote, its reaching definition:
or none if the set is empty (then clean execution fails with NameError). A history execution is trustworthy if it read each name from an execution of its reaching definition, and that execution was itself trustworthy when it wrote it. Recursion is essential: the value coming from the correct cell is not enough.
The interactive’s four failure modes violate this definition: cell 3 run twice reads x from itself rather than cell 1; editing cell 2 changes its text; deleting it makes escala come from a nonexistent cell; running 5 before 3 makes escala come from a later cell. The next result states that the definition captures what matters and requires two explicit assumptions:
- (H1) Determinism. A cell’s effect (writes and output) depends only on text and read values: it does not consult the clock, network, or an unseeded random generator.
- (H2) Visible effects. A cell interacts with others only through names in and : it does not mutate objects shared with other cells (including global random-generator state) or write files others read.
Proof
Use strong induction on execution time . Let be fresh; by definition is current text of . Take .
If exists, the last write to before was made by a fresh execution of , with . By induction, wrote the same value to as in clean execution. In that clean execution no cell between and writes (by the definition of as maximum), so reads exactly that value. In the kernel, was the last write to before , so reads it too.
If does not exist, is undefined when runs in clean execution and also in the kernel, because nothing wrote it since startup. Both executions fail in the same way when reading it.
Thus and execute the same text on the same input values and, by (H1) and (H2), produce the same writes and output.
∎The proposition says nothing if assumptions fail, and in practice they often do: lista.append(3) in another cell mutates an object without reassigning a name; a cell reading a CSV depends on a file that may have changed; unseeded weight initialization is nondeterministic; and a seeded global generator used by several cells is shared state advanced by each execution. Static name analysis is therefore approximate and the only definitive check is clean execution itself. Still, the model gives a cheap certificate readable directly on screen:
The proof is a counting argument you will do in the exercises. Notice what it does not say. Out-of-order counters do not imply hidden state: rerunning an idempotent cell such as import numpy as np does no harm. Increasing counters with gaps certify nothing either, as in the interactive, where hid a second execution of cell 3. The certificate requires the complete sequence, without gaps and nothing afterward.
The dependency graph
Reaching definitions form a graph: an edge goes from to when for some read by . Since , all edges point downward and the graph is acyclic, with document order as topological order. The graph answers what must be rerun after changing a cell: that cell and all descendants. (If editing changes what it writes, the graph changes too, and descendants in both old and new graphs are needed: a cell that stops writing x redirects its readers upstream.)
Two observations. First, editing cell 4 makes cells 5, 6, and 7 stale, while cell 7’s output, the weights, remains on screen looking unchanged: Jupyter does not mark outputs as old. Second, cell 8 breaks the model: with two cells writing X, what cell 4 reads depends on which ran last, and the graph is no longer a function of text. This is exactly the initial interactive’s situation, where two cells wrote escala.
Laboratory: a hidden-state detector
Build the previous analysis from scratch. First come and . Standard-library module ast converts text to a syntax tree; traversing it in evaluation order (assignment right-hand side before left, a for iterable before its variable) distinguishes what the cell reads externally from what it writes. Three subtleties: x += 1 reads and writes; a[i] = v requires a to exist and mutates it, so we count it as read and write; comprehensions have their own scope except the first iterable, evaluated outside it.
import ast, builtins
BUILTINS = set(dir(builtins))
class LecturasEscrituras(ast.NodeVisitor):
"""Recorre una celda en orden de evaluación y separa lo que lee de fuera de lo que escribe."""
def __init__(self):
self.lee, self.escribe = [], []
def leer(self, n):
if n not in self.escribe and n not in self.lee and n not in BUILTINS:
self.lee.append(n)
def escribir(self, n):
if n not in self.escribe:
self.escribe.append(n)
def visit_Name(self, node):
if isinstance(node.ctx, ast.Load):
self.leer(node.id)
else:
self.escribir(node.id)
def _destino(self, t):
self.visit(t)
while isinstance(t, (ast.Subscript, ast.Attribute)): # a[i] = ... o a.b = ...: muta a
t = t.value
if isinstance(t, ast.Name):
self.escribir(t.id)
def visit_Assign(self, node):
self.visit(node.value) # primero el lado derecho
for t in node.targets:
self._destino(t)
def visit_AnnAssign(self, node):
if node.value is not None:
self.visit(node.value)
self._destino(node.target)
def visit_AugAssign(self, node): # x += 1 lee x y lo escribe
base = node.target
while isinstance(base, (ast.Subscript, ast.Attribute)):
base = base.value
if isinstance(base, ast.Name):
self.leer(base.id)
self.visit(node.value)
self._destino(node.target)
def visit_For(self, node):
self.visit(node.iter)
self._destino(node.target)
for s in node.body + node.orelse:
self.visit(s)
def visit_Import(self, node):
for a in node.names:
self.escribir(a.asname or a.name.split(".")[0])
def visit_ImportFrom(self, node):
for a in node.names:
self.escribir(a.asname or a.name)
def visit_FunctionDef(self, node):
for d in node.decorator_list + node.args.defaults:
self.visit(d)
self.escribir(node.name)
interior = LecturasEscrituras()
interior.escribe = [a.arg for a in node.args.args + node.args.kwonlyargs]
for s in node.body:
interior.visit(s)
for n in interior.lee: # globales del cuerpo: se leen cuando se llama a la función
self.leer(n)
def _libres(self, nodo, locales):
for n in ast.walk(nodo):
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load) and n.id not in locales:
self.leer(n.id)
def _comprension(self, node, partes):
locales = set()
for k, g in enumerate(node.generators):
if k == 0:
self.visit(g.iter) # el primer iterable se evalúa en el ámbito de la celda
else:
self._libres(g.iter, locales)
locales |= {n.id for n in ast.walk(g.target) if isinstance(n, ast.Name)}
for c in g.ifs:
self._libres(c, locales)
for p in partes:
self._libres(p, locales)
def visit_ListComp(self, node):
self._comprension(node, [node.elt])
visit_SetComp = visit_GeneratorExp = visit_ListComp
def visit_DictComp(self, node):
self._comprension(node, [node.key, node.value])
def lecturas_escrituras(src):
v = LecturasEscrituras()
v.visit(ast.parse(src))
return v.lee, v.escribe
trampa = ["x = [2.0, 4.0, 6.0, 8.0]", "escala = 2", "x = [v / escala for v in x]",
"media = sum(x) / len(x)\nmedia", "escala = 10 # prueba rápida", 'print("media =", media)']
for i, c in enumerate(trampa, 1):
R, W = lecturas_escrituras(c)
print(f"celda {i}: lee {R!s:20} escribe {W}")
print()
for c in ["n += 1", "a[0] = b", "total = 0\nfor v in xs:\n total += v", "def f(t):\n return t * k + np.pi"]:
print(repr(c), "->", lecturas_escrituras(c))The first six lines are reads and writes used by the initial interactive, and the same rules produce graph arcs. With them, diagnosing history means applying the fresh-execution definition. This first version flags only direct causes, the specific reason a read does not come from where it should; you will implement propagation to descendants in the exercises.
def definicion_alcanzante(celdas, j, x):
"""Posición de la última celda anterior a j que escribe x en el documento actual, o None."""
for i in range(j - 1, -1, -1):
if x in lecturas_escrituras(celdas[i])[1]:
return i
return None
def diagnostico(celdas, historial):
"""historial: lista de (posición actual o None si la celda se borró, texto ejecutado)."""
ultimo = {} # nombre -> instante de su última escritura
for t, (p, s) in enumerate(historial, 1): # t es el contador de ejecución
lee, escribe = lecturas_escrituras(s)
quien = f"[{t}] celda {p + 1}" if p is not None else f"[{t}] celda borrada"
if p is None:
print(f"{quien}: ya no está en el documento")
elif s != celdas[p]:
print(f"{quien}: se ejecutó un texto que ya no es el actual")
for x in lee if p is not None else []:
r = definicion_alcanzante(celdas, p, x)
w = ultimo.get(x)
if w is None and r is not None:
print(f"{quien}: lee '{x}' antes de que la celda {r + 1} lo escriba")
elif w is not None:
pw = historial[w - 1][0]
if r is None:
origen = "una celda borrada" if pw is None else f"la celda {pw + 1}"
print(f"{quien}: lee '{x}', que en una ejecución limpia no existiría (viene de {origen})")
elif pw != r:
origen = "una celda borrada" if pw is None else f"la celda {pw + 1}"
print(f"{quien}: lee '{x}' de {origen}, pero en el documento lo define la celda {r + 1}")
for x in escribe:
ultimo[x] = t
print("Historial de partida del interactivo (la celda 3, dos veces):")
diagnostico(trampa, [(i, trampa[i]) for i in [0, 1, 2, 2, 3, 5]])
print("\nLa celda 5 se ejecutó antes que la 3:")
diagnostico(trampa, [(i, trampa[i]) for i in [0, 1, 4, 2, 3, 5]])
print("\nLa celda 2 se ejecutó, se borró y después se ejecutó la antigua celda 3, que ahora es la 2:")
sin_2 = [c for k, c in enumerate(trampa) if k != 1] # el documento actual: cinco celdas
diagnostico(sin_2, [(0, trampa[0]), (None, trampa[1]), (1, trampa[2])])The first diagnostic finds one direct cause, double execution, although the interactive marked three cells: cells 4 and 6 read from the correct cell but from an execution that was not fresh. Distinguishing cause from consequences is exactly what recursion adds to the definition.
Magics: the kernel also understands commands
IPython, the interpreter inside ipykernel, accepts commands beginning with % alongside Python. They are not Python: before running the cell, IPython rewrites them as interpreter method calls.
This translation has two practical consequences. Magics exist only in IPython kernels: a .py script with %timeit does not compile. Everything they do can also be done from ordinary code, as you will use them inside functions or in the local laboratory. The same applies to !orden: it becomes get_ipython().system('orden'), which executes it in a system shell.
These are the ones you will use daily:
| Magic | Purpose | Note |
|---|---|---|
%time expr, %%time | measure one execution, wall and CPU time | for things taking seconds |
%timeit expr, %%timeit | measure something fast repeatedly with statistics | automatically calibrates loop count |
%prun expr | profile with cProfile: time per function | -s cumulative, -l 10 |
%debug | open debugger at last exception | post mortem |
%pdb on | automatically open debugger on each exception | |
%load_ext autoreload, %autoreload 2 | reload edited modules before each cell | |
%pip, %uv | install with the kernel interpreter’s pip (or uv) | prefer uv add in the project |
%who, %whos | list kernel variables | inspect hidden state |
Measuring: %time versus %timeit
%time runs once and reports duration. %timeit solves a harder problem: accurately measuring something taking microseconds with a clock whose resolution may be worse and on a machine doing other things simultaneously. Its algorithm, readable in IPython’s code, is:
- Calibrate. Try running the expression times consecutively until total time is at least 0.2 seconds. Clock error is thus spread over calls.
- Repeat. Time a block of calls 7 times (
-r) and divide each total by : seven estimates of time per call. - Isolate. During each block disable cyclic garbage collection with
gc.disable()and restore it afterward. Standard-library moduletimeitdoes the same. - Summarize. Report mean and standard deviation of the seven estimates:
mean ± std. dev. of 7 runs, N loops each.
Step 3 makes sense with a noise model. Each measurement is , where is intrinsic code cost and everything added externally: other processes, interrupts, cache misses, and in CPython cyclic collector passes. The collector triggers when container-object allocations (lists, dictionaries, instances), net of deallocations, exceed a threshold, so a pass can occur in your block because of objects created by another cell earlier; disabling it removes the largest noise source dependent on interpreter state. The cost is that if your code creates much cyclic garbage, %timeit excludes collection cost. In that case timeit documentation suggests reenabling it in setup with timeit.Timer(stmt, "gc.enable()").
Two finer readings of the result. Since , the minimum of seven estimates is the most stable bound on , and timeit documentation recommends looking at it; IPython gives the mean, including typical interference, and stores the minimum in the object returned by %timeit -o. The is not variability of one call: each estimate averages calls, so if calls had independent deviation , each estimate’s deviation would be . It measures stability between blocks, not dispersion of your function.
An implementation from scratch fits in a few lines. To keep the cell fast in the browser we use a 0.02-second target instead of 0.2 and the sequence from timeit, with which the chosen block overshoots the target by less than powers of 10. We also use gc.callbacks to count collector triggers during measurement:
import gc, time, statistics
pasadas = [] # pasadas del recolector que caen DENTRO de un bloque medido
midiendo = False
def vigia(fase, info):
if fase == "start" and midiendo:
pasadas.append(info["generation"])
gc.callbacks.append(vigia)
def mi_timeit(f, repeticiones=7, objetivo=0.02, con_gc=False):
"""Lo que hace %timeit: calibrar N, repetir bloques de N llamadas y apagar el recolector."""
def bloque(n):
global midiendo
estaba = gc.isenabled()
if not con_gc:
gc.disable()
try:
midiendo = True
t0 = time.perf_counter()
for _ in range(n):
f()
return time.perf_counter() - t0
finally:
midiendo = False
if estaba:
gc.enable()
n, k = 1, 0
while bloque(n) < objetivo: # 1, 2, 5, 10, 20, ... como timeit.autorange (IPython: 1, 10, 100, ...)
k += 1
n = (1, 2, 5)[k % 3] * 10 ** (k // 3)
return n, [bloque(n) / n for _ in range(repeticiones)]
# resolución efectiva del reloj: el menor salto positivo entre dos lecturas seguidas
saltos = []
while len(saltos) < 30:
a, b = time.perf_counter(), time.perf_counter()
if b > a:
saltos.append(b - a)
print(f"resolución observada del reloj: {min(saltos) * 1e6:.1f} µs")
def ciclos():
for _ in range(100):
a = []
a.append(a) # un ciclo de referencias: solo lo libera el recolector
for con_gc in (False, True):
pasadas.clear()
n, ts = mi_timeit(ciclos, con_gc=con_gc)
print(f"recolector {'activo ' if con_gc else 'apagado'}: N = {n:5d}, "
f"media {statistics.mean(ts) * 1e6:7.1f} µs, mínimo {min(ts) * 1e6:7.1f} µs, "
f"pasadas del recolector durante la medida: {len(pasadas)}")
gc.callbacks.remove(vigia) # quita solo nuestro observador
gc.collect()With the collector off, no pass occurs during measurement and cyclic garbage accumulates until the block ends; with it active, passes occur within blocks and their cost is unevenly distributed across the seven estimates. Which figure you want depends on the question: isolated code cost or actual cost inside a program generating garbage.
Profiling: %prun
%timeit says how long something takes; %prun says where time goes. It runs the expression under cProfile, a deterministic profiler intercepting every function call and return, and sorts results. The key columns are tottime, time inside the function excluding calls it makes, and cumtime, including everything beneath it. Intercepting every call adds fixed per-call cost that inflates small frequently called functions; sampling profilers address this, as seen in the profiling lesson.
import cProfile, pstats, io, math
def distancia(p, q):
return math.sqrt(sum((a - b) ** 2 for a, b in zip(p, q)))
def vecino_mas_cercano(puntos, q):
return min(range(len(puntos)), key=lambda i: distancia(puntos[i], q))
def experimento(n=300):
puntos = [(math.sin(i), math.cos(3 * i), i % 7) for i in range(n)]
return [vecino_mas_cercano(puntos, q) for q in puntos[:40]]
perfil = cProfile.Profile()
perfil.enable()
experimento()
perfil.disable()
salida = io.StringIO()
pstats.Stats(perfil, stream=salida).sort_stats("tottime").print_stats(6)
print("\n".join(l for l in salida.getvalue().splitlines() if l.strip())[:2500])The table tells a story %timeit cannot: distancia is called times, and own time is shared among it, sum, and the generator expression producing squares, shown with calls because cProfile counts each generator resumption (three elements and iteration end, four per call). None is slow; repeatedly calling them from Python is. The useful optimization is not speeding up distancia, but avoiding one call per pair: vectorize all distances at once, the topic of the vectorization lesson.
Debugging: %debug after an error
When a cell raises an exception, the traceback says where, but not with what values. %debug in the next cell opens debugger pdb on the last exception, with all stack frames intact: move up and down (u, d), print variables (p, pp), see surrounding code (l), and quit (q). This is post-mortem debugging, possible because Python’s traceback object retains a reference to each frame and its locals. This is what %debug does internally, without a debugger:
import sys
def normalizar(fila):
total = sum(fila)
return [v / total for v in fila]
def preparar(tabla):
return [normalizar(f) for f in tabla]
try:
preparar([[1, 2, 3], [4, 4], [2, -2], [5, 5]])
except ZeroDivisionError:
tipo, valor, tb = sys.exc_info() # IPython lo guarda también en sys.last_traceback
marcos = []
while tb is not None: # la pila, de la celda hacia la función que falló
marcos.append(tb.tb_frame)
tb = tb.tb_next
for m in marcos:
if m.f_code.co_name == "<module>":
continue
visibles = {k: v for k, v in m.f_locals.items() if k in ("fila", "total", "tabla")}
print(f"{m.f_code.co_name:>10} línea {m.f_lineno}: {visibles}")
print("excepción:", tipo.__name__, valor)The deepest frame reveals the cause without rerunning anything: fila = [2, -2], whose sum is zero. pdb.post_mortem(tb) opens an interactive session on those frames, and %debug does the same for the last exception saved by the interpreter (sys.last_traceback) with IPython’s debugger, a pdb subclass with colors and completion. %pdb on opens it automatically on every exception, convenient during debugging and annoying otherwise.
Reloading: autoreload
Python imports each module once per process: if you edit src/atlas/metricas.py after importing it, the kernel keeps using the old version. Restarting fixes that at the cost of state, perhaps a loaded model or dataset that took minutes to prepare. The autoreload extension handles the common case:
%load_ext autoreload
%autoreload 2 # o %autoreload all: recarga todo módulo modificado antes de cada celda
from atlas.metricas import rmse
Before each cell, it checks modification times of imported module files; if any changed, it reexecutes them and, instead of creating new objects, replaces code of existing functions and class methods. Thus rmse imported with from sees the new version, and an object created earlier executes new methods. It cannot rerun what already happened: attributes placed by an old __init__ on live objects remain, and C extensions are not reloaded. You will check this in the local laboratory.
Local laboratory: the protocol, clean execution, and real magics
The following cells run in your laboratory Python, where there is a real Jupyter. The first starts a new kernel with jupyter_client, the same package used by the server, sends it a cell, and records all returned messages, as in the second figure:
import time, queue
from jupyter_client.manager import KernelManager
from jupyter_client.kernelspec import KernelSpecManager
print("kernels registrados:", sorted(KernelSpecManager().find_kernel_specs()))
km = KernelManager(kernel_name="python3")
km.start_kernel()
kc = km.client()
kc.start_channels()
kc.wait_for_ready(timeout=60)
codigo = "import sys, time\nprint(sys.executable)\nfor i in range(4):\n print('paso', i); time.sleep(0.1)\n41 + 1\n"
mid = kc.execute(codigo)
t0, eventos, respuesta, inactivo = time.time(), [], False, False
while not (respuesta and inactivo) and time.time() - t0 < 30:
for canal, leer in (("iopub", kc.get_iopub_msg), ("shell", kc.get_shell_msg)):
try:
m = leer(timeout=0.02)
except queue.Empty:
continue
if m["parent_header"].get("msg_id") != mid:
continue
c = m["content"]
resumen = c.get("execution_state") or c.get("text") or c.get("data", {}).get("text/plain") or c.get("status")
eventos.append((round(time.time() - t0, 3), canal, m["msg_type"], repr(resumen)[:60]))
respuesta |= m["msg_type"] == "execute_reply"
inactivo |= m["msg_type"] == "status" and c["execution_state"] == "idle"
for e in eventos:
print(f"{e[0]:6.3f} s {e[1]:6} {e[2]:14} {e[3]}")
kc.stop_channels()
km.shutdown_kernel(now=True)npm run lab and open the connection link.The first stream line is the kernel interpreter path, which should be your .venv path. Also note how many stream messages arrive for four print calls and when each arrives.
The second cell automates “Restart and run all.” It builds a notebook with nbformat whose saved outputs were produced with hidden state, like the initial one with cell 2 deleted, and runs it with nbclient in a clean kernel. This is the check you can put in continuous integration for each repository notebook:
import nbformat
from nbclient import NotebookClient
from nbclient.exceptions import CellExecutionError
nb = nbformat.v4.new_notebook()
nb.cells = [nbformat.v4.new_code_cell(s) for s in [
"x = [2.0, 4.0, 6.0, 8.0]",
"x = [v / escala for v in x]", # 'escala' la definía una celda que ya se borró
"media = sum(x) / len(x)\nmedia",
]]
try:
NotebookClient(nb, timeout=60, kernel_name="python3").execute()
print("el notebook se ejecuta de principio a fin")
except CellExecutionError as e:
fallo = next(i for i, c in enumerate(nb.cells) if any(o.get("output_type") == "error" for o in c.get("outputs", [])))
print(f"falla la celda {fallo + 1}:", str(e).strip().splitlines()[-1][:120])
print("contadores tras la ejecución limpia:", [c.get("execution_count") for c in nb.cells])npm run lab and open the connection link.The last cell uses magics from code through the same API to which IPython translates %. Inside the laboratory you are already in an IPython kernel; in ordinary Python, InteractiveShell.instance() creates an IPython interpreter for the occasion:
import os, sys, time, shutil, tempfile, textwrap
from pathlib import Path
from IPython import get_ipython
from IPython.core.interactiveshell import InteractiveShell
ip = get_ipython() or InteractiveShell.instance()
for linea in ["%timeit f(x)", "!pip install rich", "%pip install rich", "datos = !dir"]:
print(f"{linea:20} -> {ip.transform_cell(linea).strip()}")
print("\nintérprete del kernel :", sys.executable)
print("'pip' según el PATH :", shutil.which("pip"))
# %timeit -o devuelve el objeto con todas las medidas
r = ip.run_line_magic("timeit", "-o -q sorted(range(2000, 0, -1))")
print(f"\n%timeit: N = {r.loops} bucles, {r.repeat} repeticiones, media {r.average * 1e6:.1f} µs, "
f"desviación {r.stdev * 1e6:.2f} µs, mínimo {r.best * 1e6:.1f} µs")
# %prun -r devuelve las estadísticas de cProfile
def lento():
return sum(sorted([i * i % 97 for i in range(20000)]))
ip.user_ns["lento"] = lento # las magics evalúan en el espacio de nombres del intérprete
st = ip.run_line_magic("prun", "-q -r lento()")
st.sort_stats("tottime").print_stats(3)
# autoreload sobre un paquete de juguete
tmp = Path(tempfile.mkdtemp())
(tmp / "milab").mkdir()
(tmp / "milab" / "__init__.py").write_text("")
modulo = tmp / "milab" / "metricas.py"
def escribir(cuerpo, segundos):
modulo.write_text(textwrap.dedent(cuerpo), encoding="utf-8")
t = time.time() + segundos
os.utime(modulo, (t, t)) # fecha de modificación distinta: autoreload la compara
escribir("""
def error(y, yhat):
return sum((a - b) ** 2 for a, b in zip(y, yhat)) / len(y)
class Escalador:
def __init__(self, k):
self.k = k
def aplicar(self, x):
return [self.k * v for v in x]
""", 0)
sys.path.insert(0, str(tmp))
ip.run_line_magic("load_ext", "autoreload")
ip.run_line_magic("autoreload", "2")
from milab.metricas import error, Escalador
e = Escalador(2)
print("\nantes :", error([1, 2, 3], [1, 2, 5]), e.aplicar([1, 2]), "k =", e.k)
escribir("""
def error(y, yhat):
return sum(abs(a - b) for a, b in zip(y, yhat)) / len(y)
class Escalador:
def __init__(self, k):
self.k = 10 * k
def aplicar(self, x):
return [self.k * v + 0.5 for v in x]
""", 5)
ip.run_line_magic("autoreload", "now") # lo que el kernel hace solo antes de cada celda con %autoreload 2
print("después :", error([1, 2, 3], [1, 2, 5]), e.aplicar([1, 2]), "k =", e.k)npm run lab and open the connection link.Read the last line carefully. error now calculates mean absolute error even though imported with from before the change, and object e, created earlier, runs the new aplicar (adds 0.5). But e.k remains 2 rather than 20: the new __init__ has not run for an existing object. When something behaves strangely after reload, the usual remedy is restart.
Exploration and consolidation
All this suggests a workflow where each thing lives where it works best.
The notebook explores. It is the place to load data, inspect distributions, try three ideas in ten minutes, and plot. Hidden state is an acceptable price there because speed matters.
The package consolidates. Once a function is used twice or a result will appear in a report, code moves to src/<paquete>/, the project package uv installs in editable mode, and is imported from the notebook with autoreload active. In the package code has a name, documentation, tests, and one version. Copying a function between notebooks yields, weeks later, three slightly different versions and no way to know which generated each result.
The notebook records. Once consolidated, the notebook becomes a results notebook: import from the package, run, display. Cells are short, mostly calls to tested functions, making top-to-bottom execution easy. This is the lab notebook idea you will formalize when designing a research project structure.
Hygiene
Three habits make a notebook trustworthy:
- Restart and run all before trusting a result. This is the only way the counter corollary holds by construction. If it takes too long, heavy computation should save results to disk from a script. In continuous integration,
jupyter nbconvert --to notebook --execute notebook.ipynbor the laboratory’sNotebookClientdoes the same headlessly. - Fix randomness. Assumption (H1) requires determinism, and an explicit seed at the notebook start makes clean execution reproducible. But a global generator is shared state (H2): rerunning a cell drawing from it produces different numbers. Robust practice creates the generator where used, one per experiment, with
rng = np.random.default_rng(semilla). - Clear outputs before git. An
.ipynbis JSON containing outputs, including base64 images. With outputs, every execution changes the file even without code edits: diffs become unreadable and the repository grows with each figure.jupyter nbconvert --clear-output --inplace notebook.ipynbclears them manually, andnbstripout --installinstalls a git filter doing so at each commit. For a truly readable diff,jupytextpairs each notebook with a.pyin# %%cell format, which you version.
Frontier: reactive notebooks
The proposition suggests a different design: if the environment knows the dependency graph, it can ensure all executions are fresh. This is what reactive notebooks do, with marimo the most widespread Python example. According to its documentation, its model is exactly the figure’s reactive mode:
- It analyzes each cell without executing it to find global names it defines and references, building a directed acyclic graph.
- Running a cell automatically runs all cells referencing what it defines in topological order, regardless of page position. In lazy mode it marks them stale instead.
- Deleting a cell deletes its variables from memory.
- It requires each global variable to be defined by one cell: interactive cell 8 is an error, because two definitions make the graph execution-order dependent.
- It does not track mutations:
datos.append(x)in another cell does not notify readers ofdatos. This is assumption (H2), and its documentation recommends mutating an object only in its defining cell. - It saves the notebook as an ordinary
.pyfile that can be imported, run as a script, and compared in git without filters.
In this lesson’s terms, a reactive notebook maintains by construction that each cell’s last execution is fresh (or the cell is marked stale in lazy mode), provided (H2) holds, in exchange for writing cells without cross-cell reassignments. It does not eliminate the need for seeds or care with external files, which remain outside the graph.
Common mistakes
Exercises
x = 2 with counter [3], x = 5 with [1], x = x + 1 with [5], and y = x * 10 with [2]. No cell was deleted, no output cleared, nothing edited, and the kernel has run nothing else since startup. What are x and y now in the kernel?!pip install rich, which ends with Successfully installed rich, and then import rich fails with ModuleNotFoundError. What happened and what should you have done?torch.compile or numba). What would you use for each?%timeit and module timeit call gc.disable(). What is the main reason?%timeit f() without options on a function always taking exactly 0.9 ms. IPython tries calls until a block takes at least 0.2 s, then times 7 blocks of calls. Ignoring other costs, how many seconds does the cell take in total?len(datos), then press interrupt. A ends with KeyboardInterrupt. What happens to B?%autoreload 2 active, you created m = Modelo(capas=3). You edit modelo.py: __init__ now stores self.capas = capas + 1 and method resumen() also prints parameter count. In the next cell you run m.resumen(). What happens?Step 1 of 4. How many executions have occurred since startup?
stale_cells(cells, order). cells is the list of current cell texts in document order. order is history since startup: a list of (posición, texto) pairs, where posición is the cell index in cells (from 0), or None if deleted, and texto is its text when run. Return sorted positions whose last execution is not fresh under the lesson definition; exclude cells never run. Use reads_writes(src), already implemented to return read and written names, and take the reaching definition as the last previous cell in the current document whose text writes the name. Assume no cell raises an exception.import ast, builtins
_B = set(dir(builtins))
def reads_writes(src):
"Nombres que la celda lee antes de escribirlos y nombres que escribe (versión simplificada)."
reads, writes = [], []
class V(ast.NodeVisitor):
def visit_Name(self, n):
if isinstance(n.ctx, ast.Load):
if n.id not in writes and n.id not in reads and n.id not in _B:
reads.append(n.id)
elif n.id not in writes:
writes.append(n.id)
def visit_Assign(self, n):
self.visit(n.value)
for t in n.targets:
self.visit(t)
def visit_AugAssign(self, n):
if isinstance(n.target, ast.Name) and n.target.id not in writes and n.target.id not in reads:
reads.append(n.target.id)
self.visit(n.value)
self.visit(n.target)
def visit_ListComp(self, n):
self.visit(n.generators[0].iter)
local = {t.id for g in n.generators for t in ast.walk(g.target) if isinstance(t, ast.Name)}
for t in ast.walk(n.elt):
if isinstance(t, ast.Name) and t.id not in local:
self.visit(t)
V().visit(ast.parse(src))
return reads, writes
def stale_cells(cells, order):
# recorre el historial en orden, decide si cada ejecución es fresca
# y devuelve las posiciones cuya última ejecución no lo es
return []Summary
- Architecture. Client, server, and one kernel per notebook communicate via JSON messages over five channels: shell for requests and replies, IOPub to broadcast output and state, stdin for
input(), control to interrupt and shut down, heartbeat to check kernel life. The kernel assigns the execution counter. - The project kernel is a
kernel.jsonwhoseargvpoints to.venvPython. Always verifysys.executable, and install dependencies withuv add, not!pip. - Hidden state is the difference between kernel and clean execution. Under determinism and visible effects, fresh executions reproduce clean execution; counters with nothing afterward certify it, and a gap is a warning.
- Magics:
%timefor one long run,%timeitfor something short (calibrates , repeats 7 times, and disables cyclic collection),%prunto find where time goes,%debugto inspect the stack after error, and%autoreload 2to develop modules without restart while knowing its limits. - Workflow: the notebook explores and records, the package consolidates. Before trusting a number, restart and run all; before git, clear outputs. Reactive notebooks such as marimo apply the dependency graph automatically in exchange for one definition per variable.