IPython Magic Commands
Line magics are single-word commands prefixed with a percent sign, such as %run or %timeit, that act like functions accepting the rest of the line as arguments. Cell magics, prefixed with two percent signs and described in the next chapter, process multi-line blocks. Magics are a trademark feature of IPython: they configure the interpreter, benchmark code, inspect state, and bridge to the operating system, all without leaving the session.
Everyday Line Magics
A practical core set covers most needs:
%run script.py— execute a file and import its names into the interactive namespace.%timeit statement— time a small snippet with sophisticated loop calibration;%%timeper cell is covered later.%whoand%whos— list the variables you have created, briefly or in detail.%history— show previous input, optionally for specific line ranges or sessions.%load file.py— insert the contents of a file, URL, or module into the current cell.%xmode, %debug— switch traceback detail level and start post-mortem debugging.
Running and timing a function illustrates the pattern:
In [1]: def total(n):
...: return sum(range(n))
In [2]: %timeit total(10_000)
198 µs ± 4.2 µs per loop (mean ± std. dev. of 10 runs, 1000 loops each)
In [3]: %time total(10_000)
CPU times: user 152 µs, sys: 5 µs, total: 157 µs
Wall time: 163 µs
List and Time Objects
After a few minutes of exploratory work the namespace fills up. %who prints bare names, while %whos formats a table with types and values — a cheap alternative to whos in any debugger:
In [4]: %who
data total
In [5]: %whos
Variable Type Data/Info
-------------------------------
data ndarray 100x3: 2400 bytes
total function <function total>
Getting Help on Magics
Magics are self-documenting. Add ? to any magic for the full description, use %lsmagic to list every available command, and let tab completion suggest names while you type:
In [6]: %lsmagic
Available line magics:
%alias %config %debug %history %load %lsmagic %pwd
%run %store %time %timeit %who %whos ...
In [7]: %timeit?
Summary
Line magics such as %run, %timeit, %who, %history, and %load control interactive sessions; discover them with %lsmagic and read their documentation with a trailing ?.