Sub topic 3
Speed up your workflow with magic commands
Assume you know basic Python, can use a terminal, and have JupyterLab installed with pandas and matplotlib. This chapter focuses on notebook behavior, reproducibility, and safe sharing.
Use magic commands
Magic commands are Jupyter-specific commands that begin with % for one line or %% for a whole cell. They are useful for notebook configuration and inspection.
%matplotlib inline
%load_ext autoreload
%autoreload 2%matplotlib inline displays plots beneath the cell. %autoreload 2 reloads imported local modules when their source files change. These commands affect the current kernel, not every notebook automatically.
Avoid hidden state and out-of-order execution
A kernel keeps variables and imports in memory. Therefore, a cell can succeed because an earlier cell ran, even when the notebook appears to be missing a step. Running cells out of order creates hidden state.
Use Kernel > Restart Kernel and Run All Cells before sharing results. This catches missing imports, stale variables, and cells that depend on an accidental execution order.
flowchart TD
A[Edit notebook] --> B[Restart kernel]
B --> C[Run all cells in order]
C --> D{Does it succeed?}
D -->|No| E[Fix missing or stale state]
E --> B
D -->|Yes| F[Save and share]Record dependencies
Record the exact packages in the active environment:
python -m pip freeze > requirements.txtAnother person can then create an environment and install those versions with python -m pip install -r requirements.txt. Run the command from the environment used by the notebook. A common error is freezing a different Python installation.
Keep notebooks manageable in Git
Notebook files store code, outputs, and metadata. Large outputs make Git diffs difficult to review. In a repository, install nbstripout and configure it as a Git filter:
python -m pip install nbstripout
nbstripout --installThis removes cell outputs before commits. Keep important figures as deliberate artifacts, not accidental output.
Export and run notebooks
Use nbconvert to create a static report or verify that every cell runs in order:
jupyter nbconvert --to html analysis.ipynb
jupyter nbconvert --to notebook --execute --inplace analysis.ipynbThe second command overwrites the notebook with newly generated outputs, so commit or copy the file first if the current results matter.
Protect a Jupyter server
Jupyter normally includes a token in its browser URL. Treat that URL like a password. Do not paste it into public chats or disable authentication on an exposed server. Remote access should use encrypted transport, such as an SSH tunnel, and a server should bind only to interfaces that need access.
Exercise
What is the safest way to check that a notebook does not depend on hidden state?
Show answer
Restart its kernel and run every cell from the beginning in order.