TL;DR Twelve lines of notebook setup nobody reads is a symptom. A custom IPython magic — line (
%labenv), cell (%%labsql), or both at once (@line_cell_magic) — collapses it into one word. You need four things:@magics_class+register_magics,magic_argumentsfor argparse-grade flags,%load_ext/the startup folder for always-on availability, and the three-output-channels model that tells you where your magic’s output actually goes. Verified on IPython 8.18.1 (2026-12-02).
Every notebook begins the same way: connect to the database, set the plot style, load project config — every single session, twelve lines nobody reads. A custom IPython magic collapses that into one word.
Verified on IPython 8.18.1 / Python 3.9 (2026-12-02); every behaviour shown was executed in a live shell before publishing, not remembered.
The smallest useful magic #
from IPython.core.magic import Magics, magics_class, line_magic, cell_magic, line_cell_magic
@magics_class
class LabMagics(Magics):
@line_magic
def labenv(self, line):
"""%labenv KEY=VALUE — set a project-wide env var."""
key, _, value = line.partition("=")
import os
os.environ[key.strip()] = value.strip()
return f"labenv: {key.strip()}={value.strip()}"
@cell_magic
def labsql(self, line, cell):
"""%%labsql mydb — echo the (simulated) query for review."""
return f"RUN[{line}]: {cell.strip()[:40]}..."
from IPython import get_ipython
get_ipython().register_magics(LabMagics)Run it and %lsmagic immediately lists %labenv and %%labsql alongside the built-ins — and, once you’ve added the dual-mode magic below, %labrun joins them. Custom magics are first-class citizens, not a hack. The docstring you write becomes inline help (%labenv?).
Line vs cell vs both #
IPython distinguishes three shapes, and one decorator each:
| Decorator | Usage | What line holds |
|---|---|---|
@line_magic |
%labenv LAB=on |
everything after the name |
@cell_magic |
%%labsql mydb + body |
the first line of the cell |
@line_cell_magic |
both of the above | the first line — plus cell, either None or the body |
The dual-mode magic is the one worth learning, because it reads exactly like the built-ins you already use: %time 1+1 times a line; %%time over a cell times the whole block. Here is a command in both moods:
@line_cell_magic
def labrun(self, line, cell=None):
"""%labrun x | %%labrun x -- one magic, two modes."""
if cell is None:
return f"line mode: {line}"
return f"cell mode[{line}]: {len(cell.splitlines())} lines"Verified: %labrun quick → line mode: quick; %%labrun quick + 3 lines → cell mode[quick]: 3 lines. This is how %time, %timeit and %prun behave (%run and %load are line-only).
Arguments without string-soup #
Don’t split flags by hand — magic_arguments gives magics argparse-grade handling:
from IPython.core.magic_arguments import magic_arguments, argument, parse_argstring
@magic_arguments()
@argument("name")
@argument("--verbose", action="store_true")
@line_magic
def labgreet(self, line):
"""%labgreet NAME [--verbose]"""
args = parse_argstring(self.labgreet, line)
return f"hello {args.name}" + (" (verbose)" if args.verbose else "")Verified: %labgreet ana --verbose → hello ana (verbose). Misuse raises clean, argparse-shaped errors: a cell magic called with no body says %%labsql is a cell magic, but the cell body is empty.; a missing positional says the following arguments are required: name. Raise UsageError yourself for exactly that quality of failure message.
Where the output actually goes (the part nobody gets right on the first try) #
A magic has three channels, and they behave differently:
- A returned string shows up in the cell’s
Out[]— like%labenvabove. - A
print()writes to stdout — invisible inOut[], visible in the stream. - A returned
DisplayObject(HTML,Markdown) goes to the display hook — it renders, and it still lands inOut[]as the cell’s result. What returnsNoneis a baredisplay()call or a magic that returns nothing at all.
That distinction bites in real notebooks. Verified example: a cell magic returning Markdown("**hello**") renders bold text and its result is the Markdown object; %%capture cap then reveals the capture holds it as a mime record — a dict with a text/markdown payload, not a plain string — while the capture cell’s own value is None only because %%capture itself returns nothing. Print when you want capture-able text; return the display object when you want it rendered — and know which contract you used.
Ship it: %load_ext + the startup folder
#
Keep your magics in a plain lab_magics.py (importable file, with def load_ipython_extension(ipython): ipython.register_magics(LabMagics) at the bottom), then two one-liners make them permanent:
%load_ext lab_magics # from anywhere on the path — reloadable with %reload_extand, for “always there”, drop the file into your IPython startup folder — exactly the mechanism covered in Jupyter: automatically load code with the IPython startup folder. The two techniques are one system: the startup folder loads the file, the file registers the magics, and every notebook opens with %labenv, %%labsql already available before the first cell.
Gotcha shelf #
- Magic names are case-sensitive, but capitals do work (
%%HTMLand%%SVGare built-ins) — pick a convention; don’t rely on case to differentiate. - Subclass
Magicsdirectly unless you know otherwise —@magics_classcollects only the methods you decorated in that class. - After editing the file:
%reload_ext lab_magicsusually works — but stateful magics (open connections) can linger; restarting the kernel is the honest reset. - Don’t shadow a built-in magic name;
%lsmagicis the authority — if your name isn’t there, your registration didn’t happen.
Your dashboard #
| Situation | Tool |
|---|---|
| Same 12 setup lines in every notebook | a %lab line magic |
| Repeating multi-line boilerplate (SQL, HTML headers) | a %% cell magic |
| One command both inline and over a block | @line_cell_magic |
| Flags like a real CLI | magic_arguments + parse_argstring |
| Always-on availability | %load_ext + startup folder |
“Why is my magic’s output invisible in Out[]?” |
it only printed or called display() — prints never enter Out[]; a returned value or object does |
Behaviours verified live in a shell: IPython 8.18.1, Python 3.9, 2026-12-02 (a custom %labenv / %%labsql / %labrun class registered and exercised end-to-end).
The next step is a full inventory of the built-ins worth using daily — %run, %load, %%capture, %%markdown, %autoreload and friends — in Helpful Jupyter magics: the everyday tour.