Sub topic 9
Speed up your workflow with magic commands
This chapter assumes you have a working virtual environment with JupyterLab, pandas, and matplotlib installed, and that you can run cells in a notebook registered to that environment. It also assumes basic Python syntax and a comfortable terminal habit. You do not need to know anything about IPython internals.
What magic commands are
Jupyter notebooks run code through a kernel. For Python, that kernel is IPython. IPython adds a set of special commands called magics that are not valid Python. They control the notebook session, time your code, run shell commands, and change how output is displayed.
Magics come in two forms:
- A line magic starts with one
%and applies to the rest of that line only. - A cell magic starts with two
%%, must be the first line of the cell, and applies to the whole cell body.
The % prefix is optional for line magics when the name does not clash with a Python variable, because of a setting called automagic. Writing the % is clearer, so this chapter always uses it.
Magics belong to IPython, not to Python. If you copy notebook code into a plain .py file, lines like %matplotlib inline raise a SyntaxError. Keep this in mind when you move code out of a notebook into a module.
Discover what is available
Two magics list the others.
%lsmagicThis prints every line and cell magic in the current kernel. To read the documentation for one magic, add a question mark:
%timeit?The ? suffix opens a help pane with the signature and options. Use it whenever a flag in this chapter is unclear.
Display: %matplotlib inline
The Python example from this tutorial's plan sets up plotting like this:
%matplotlib inline
%load_ext autoreload
%autoreload 2%matplotlib inline selects the matplotlib backend. A backend is the component that turns a figure into something you can see. The inline backend renders each figure as a static image directly below the cell that produced it.
In recent JupyterLab and ipykernel versions, inline is already the default for notebooks. Running the magic is still harmless and makes the intent explicit. Run it once, near the top of the notebook, in the same cell as your imports.
Two alternatives exist:
| Magic | Result | Needs |
|---|---|---|
| `%matplotlib inline` | Static images below each cell | Nothing extra |
| `%matplotlib widget` | Interactive figure with pan and zoom | The `ipympl` package |
| `%matplotlib qt` | Separate desktop window | A Qt package and a local display |
The widget backend is useful for exploring a plot, but it does not appear in exported HTML as an interactive figure unless the export is set up for widgets. For reports, prefer inline.
Reload your own code: %autoreload
As a project grows, you will move helper functions out of the notebook into a local module, for example helpers.py beside the notebook. Python imports a module once per kernel session. If you edit helpers.py afterward, the notebook keeps using the old version until you restart the kernel.
%autoreload fixes this:
%load_ext autoreload
%autoreload 2%load_ext autoreloadloads the extension. You do this once per kernel session.%autoreload 2reloads all imported modules before every cell executes, except those excluded with%aimport.
The mode numbers are:
| Mode | Behavior |
|---|---|
| `0` | Disable autoreloading |
| `1` | Reload only modules imported with `%aimport` |
| `2` | Reload all modules before each cell runs |
| `3` | Like 2, and also pick up newly added objects |
Here is a small worked example. Create helpers.py next to the notebook:
# helpers.py
def clean_columns(df):
df = df.copy()
df.columns = [c.strip().lower() for c in df.columns]
return dfIn the notebook:
import pandas as pd
from helpers import clean_columns
df = pd.DataFrame({" Revenue ": [10, 20], "Region": ["N", "S"]})
clean_columns(df).columns.tolist()The result is ['revenue', 'region']. Now edit helpers.py so the function also replaces spaces with underscores, save it, and rerun the last cell. With %autoreload 2 active, the new behavior appears without a restart.
Autoreload has limits. It cannot update instances of a class that already exist, because those objects still point at the old class definition. It can also behave oddly with modules that run side effects on import. When results look wrong after an edit, restart the kernel and run all cells. That restores a known state, as the later chapter on hidden state explains.
Measure speed: %timeit and %time
Data work often raises the question of which of two approaches is faster. Two magics answer it.
%time runs a statement once and reports wall time and CPU time:
import numpy as np
data = np.random.default_rng(0).normal(size=1_000_000)
%time data.sum()%timeit runs the statement many times and reports the mean and standard deviation, which is more reliable for short operations:
%timeit data.sum()The cell version, %%timeit, times a whole block:
%%timeit
total = 0.0
for x in data[:10_000]:
total += xTwo things to remember:
%timeitchooses the number of loops itself. Override it with-n(loops per run) and-r(number of runs), for example%timeit -n 100 -r 5 data.sum().- Variables assigned inside
%%timeitdo not persist in the notebook. The cell runs in a throwaway scope for the timing, so do not rely ontotalafterward.
Use %time for slow, one-off operations such as loading a big file. Use %timeit for fast operations that need repeated measurement.
Run shell commands: ! and %%bash
A line that starts with ! runs in your system shell:
!ls data
!python --versionYou can pass Python values into a shell command with braces:
filename = "data/sales.csv"
!head -n 3 {filename}You can also capture shell output as a list of strings:
lines = !wc -l data/sales.csv
linesThe %%bash cell magic runs the whole cell as a Bash script. Use it for multi-line scripts:
%%bash
for f in data/*.csv; do
echo "$f: $(wc -l < "$f") lines"
doneShell commands are not portable. !ls and %%bash fail on a default Windows setup, so a notebook shared across operating systems should use Python (pathlib, os) for file work instead.
Install packages: %pip
Installing packages from a notebook has a classic trap. !pip install pandas may call a pip that belongs to a different Python than the one running your kernel, so the package installs into the wrong environment and import still fails.
The %pip magic avoids this. It always installs into the environment of the running kernel:
%pip install seabornAfter installing a package that was already imported, restart the kernel so Python loads the new version.
Treat %pip as a quick experiment tool. For a project others will reproduce, install from the terminal inside the virtual environment and record the result with python -m pip freeze > requirements.txt. Installs buried in notebook cells are easy to miss and make the environment depend on cell execution order.
%conda exists as the equivalent for conda environments. This tutorial uses venv, so you do not need it.
Inspect the session: %who, %whos, %env, %pwd
A few magics show state without writing any Python.
%wholists the names of variables in the session.%whoslists them with type and size information, which helps when a DataFrame is larger than you expected.%pwdprints the working directory. Relative paths such asdata/sales.csvresolve against this directory.%cd pathchanges it.%env NAMEshows an environment variable, and%env NAME=valuesets it for the kernel process.
%whos%whos is a useful first step when you suspect hidden state, because it shows exactly which variables exist right now.
Save and reuse cell code: %%writefile and %run
%%writefile writes the cell body to a file instead of running it:
%%writefile helpers.py
def clean_columns(df):
df = df.copy()
df.columns = [c.strip().lower().replace(" ", "_") for c in df.columns]
return dfThis is a convenient way to promote a function from experiment to module. Note that it overwrites an existing file without asking. Use -a to append.
%run script.py executes a Python file inside the notebook's namespace, so the variables it defines become available afterward. Prefer import with autoreload for reusable code, and keep %run for one-off scripts.
A decision guide
The following diagram summarizes which magic to reach for.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `UsageError: Line magic function '%x' not found` | Typo, or the extension is not loaded | Run `%lsmagic`, or load the extension with `%load_ext` |
| `UsageError: Cell magic '%%x' must start at the first line` | A comment or blank line precedes the cell magic | Move the magic to line 1 of the cell |
| `ModuleNotFoundError` after `!pip install` | `pip` belongs to another Python | Use `%pip install` and restart the kernel |
| `SyntaxError` on a `%` line in a `.py` file | Magic used outside IPython | Replace it with plain Python or remove it |
| Edits to `helpers.py` have no effect | Autoreload not loaded, or an existing class instance | Run `%load_ext autoreload`, recreate the objects, or restart |
Exercises
Exercise
You edit helpers.py and rerun a notebook cell that calls a function from it, but the old behavior still appears. Which two commands, run in a cell, make the notebook pick up future edits automatically?
Show answer
Run %load_ext autoreload to load the extension and %autoreload 2 to reload all imported modules before each cell runs. If an object was created from a class in the old module, recreate it or restart the kernel.
Exercise
A colleague runs !pip install seaborn in a notebook, but import seaborn still raises ModuleNotFoundError. Explain the likely cause and give the better command.
Show answer
The pip on the shell's path probably belongs to a different Python than the kernel's, so seaborn was installed into the wrong environment. %pip install seaborn installs into the environment of the running kernel. If the package was already imported, restart the kernel afterward.
Exercise
You want to compare two ways of summing a NumPy array and need a reliable timing. Which magic do you use, and why not %time?
Show answer
Use %timeit, or %%timeit for a multi-line block. It runs the code many times and reports a mean and standard deviation, which smooths out noise. %time runs the code once, so its result is unreliable for fast operations.