zallery
zallery builds an example gallery for Zensical documentation sites from plain Python scripts.
Each example is a jupytext percent-format .py
file. zallery runs it once in a Jupyter kernel, renders it as a notebook-style
Markdown page with code, outputs, and .py/.ipynb downloads, and writes an index
page with one card per example. Every matplotlib figure comes out twice, for the
light and the dark color scheme, from that single run.
Installation
uv add --dev zallery
Or with pip:
pip install zallery
Quick start
Add a [tool.zallery] table to the project's pyproject.toml (an empty table is
enough, every key has a default):
[tool.zallery]
examples = "docs/examples"
Create a section with one example:
mkdir -p docs/examples/my-section
printf '# My section\n\nIntro.\n' > docs/examples/my-section/_section.md
cat > docs/examples/my-section/hello.py <<'EOF'
# %% [markdown]
# # My example
#
# Short description.
# %%
print("hi")
EOF
Build the gallery from anywhere inside the project:
uv run zallery
This writes docs/examples/index.md (the card index) and
docs/examples/_built/my-section/hello.md with its images and downloads. Add them
to the site navigation like any other page; both are generated, so keep them and
the cache directory out of version control.
Command line
zallery [--no-run] [--no-cache] [EXAMPLE ...]
- With no arguments, every example is executed, or restored from cache when its source and the cache fingerprint are unchanged.
- Name example scripts to run only those. The whole gallery is still rendered: the others are restored from cache if present, or rendered with code and Markdown only.
--no-runexecutes nothing, to iterate on prose or layout.--no-cacheexecutes the selected examples even when a cached result exists; the result replaces the cache entry.
python -m zallery is equivalent.
Writing examples
Examples live under <examples>/<section>/<name>.py.
- The first Markdown heading of an example is its page title; the next Markdown paragraph is the summary shown on its index card.
- A section folder may contain a
_section.mdwhose first heading becomes the section title on the index page. - An
_index.mdin the examples root replaces the default header of the index page. - A leading numeric prefix (
01_io/,02_first.py) orders sections and examples and is stripped from the built names. - Files and folders starting with
_are skipped. - Tag a cell with
thumbnailto use its first image output on the index card. - Tag a cell with
collapse(orcollapse: <title>) to hide its code behind a collapsed callout, handy for setup the reader can expand on demand. The cell still runs, and its output renders normally below the callout. The callout defaults to theexampleadmonition; pick another type withcollapse[<type>]orcollapse[<type>]: <title>, where<type>is any admonition name Zensical understands (warning,tip,note, ...). - Tag consecutive code cells with
tab: <title>to show them as tabs, each with its code and its output. An untagged cell, code or Markdown, ends the set of tabs. Every tab runs, in order and in the same kernel. Thecollapseandannotatetags are ignored on a tab cell. - Tag a code cell with
title: <text>to show a title above its code, and withhl_lines: <lines>to highlight lines: numbers and ranges separated by spaces, such ashl_lines: 2 4-5. Line 1 is the first line of the cell. - Tag a code cell with
annotateto attach notes to its lines. End a line with a comment such as# (1)!, and write the notes as a numbered list in the Markdown cell that follows. zallery writes that cell directly under the code, above the output, which is where Zensical reads the notes from. - A failing cell does not abort the build: its traceback is rendered on the page.
Light and dark figures
Every example runs once, under a light matplotlib style. Each figure is then
re-rendered for dark mode without re-executing anything: zallery swaps the theme
colors (figure background, axes background, black foreground) and the default
diverging colormap (coolwarm to berlin) on the drawn artists, prints a second
PNG, and restores the exact properties it changed. Both PNGs land on the page, and
the site shows the one matching the reader's color scheme.
What this means when writing an example:
- Read backgrounds from matplotlib rather than hardcoding them, for example
mpl.rcParams["figure.facecolor"]. Figures created withplt.subplotsorplt.figurealready get this background. Pure black is a theme color wherever it appears (text, lines, line markers, and backgrounds). Per-element colors (scatter(c="black"), collections) are left alone. Pure white and any other explicit color are kept as is. - A figure whose background is pure black is taken as drawn for a dark page: its black is swapped as background and its white as text for both pages, pure-white data colors included. This cannot work at a finer grain, since one figure can hold both a plot on black with white text and a regular plot.
- Do not branch on the theme in the example: there is only one run. Pick colormaps that read well on both backgrounds, or swap them with a hook (below).
- Images not drawn by matplotlib (PIL images, screenshots) are shown unchanged in both themes.
To give each color scheme its own default colors, set a palette for each one in
pyproject.toml:
[tool.zallery.light]
matplotlib.palette = "Dark2"
[tool.zallery.dark]
matplotlib.palette = "Set2"
A palette is the name of a listed matplotlib colormap ("Set2", "tab10") or a
list of colors. Examples run with the light palette as matplotlib's color cycle. On
the dark page, each color of the light palette is replaced by the color at the same
position of the dark palette, so the dark palette needs at least as many colors.
- Without a light palette, the light page uses matplotlib's default cycle. Without a dark palette, both pages show the light one.
- Palette colors are also replaced in scatter plots, filled areas and other collections, unlike the theme colors above. Colormapped data keeps its colormap.
- Only exact palette colors are replaced. A color derived from one (lightened, or desaturated as seaborn does for bars) stays as drawn. A color you set yourself that equals a palette color is replaced too.
When the built-in swap is not enough, point the hook key at a module of the
project that defines gallery_retheme(fig, theme). It runs in the kernel after a
theme swap and returns a context manager that restores what it changed, also when
printing fails. It is called with "dark" before the dark rendering, and with
"light" when a figure drawn on black is first converted to light. There is no
call to undo: the returned context manager does that.
from zallery.theme import swap_cmaps
SWAPS = {"inferno_r": "inferno"}
def gallery_retheme(fig, theme):
"""Draw with `inferno_r` on the light page, `inferno` on the dark page."""
mapping = SWAPS if theme == "dark" else {dark: light for light, dark in SWAPS.items()}
return swap_cmaps(fig.findobj(), mapping)
zallery.theme.swap_cmaps and zallery.theme.swap_colors take the figure's
artists and a mapping, and each returns such a context manager; combine several
with contextlib.ExitStack.
Configuration
zallery reads the [tool.zallery] table of the nearest pyproject.toml above the
working directory; relative paths resolve against that file's directory. All keys
are optional:
| Key | Default | Meaning |
|---|---|---|
examples |
docs/examples |
Directory of example sections. |
built |
<examples>/_built |
Where rendered pages and images go. |
cache |
.gallery-cache |
Execution/render cache. |
binder_repo |
unset | owner/repo for the Binder launch buttons. |
hook |
unset | Dotted name of a module, importable from the project root, defining gallery_retheme(fig, theme). |
fingerprint |
["uv.lock"] |
Files whose change invalidates the cache. |
light, dark |
none | Tables of presets for each color scheme. Their key so far is matplotlib.palette: see Light and dark figures. |
The git ref stamped into Binder URLs comes from the ZALLERY_BINDER_REF
environment variable (default main).
A cached example is reused while its source, the Python version, the configuration,
the fingerprint files, the hook module, and the zallery sources are all unchanged.
Zensical integration
zallery writes Markdown pages; the Zensical site provides the rest, in
zensical.toml and a stylesheet:
-
Markdown extensions
attr_list,md_in_html,admonition,pymdownx.detailsandpymdownx.superfences. -
naventries for the index page and the built pages. -
Two CSS rules so each image shows in its own color scheme:
[data-md-color-scheme="slate"] img[src$="#only-light"] { display: none; } [data-md-color-scheme="default"] img[src$="#only-dark"] { display: none; }
-
Fallback thumbnails for examples without a
thumbnailcell, at<examples>/_assets/default_thumb.svgand<examples>/_assets/default_thumb_dark.svg. -
Optionally, styles for the classes zallery emits:
examples-cardsandexamples-card-summaryon the index page,gallery-outputandgallery-rich-outputaround cell outputs. This repository'szensical.tomland stylesheet are a working setup, with notebook-like pandas tables; the ConfUSIus stylesheet also styles scikit-learn outputs. xarray views need no site styles: zallery adapts them to the color scheme itself.
Relationship to ConfUSIus
zallery is extracted from ConfUSIus, where it builds the documentation's example gallery. It does not depend on ConfUSIus and makes no assumption about what the examples compute.
Development
uv sync # install dependencies
just test # run tests
just pre-commit # run lint, format, type checks, docstring checks
just serve-docs # build the example gallery in docs/examples and serve the docs
License
BSD-3-Clause. See LICENSE.
Metadata
Release files for zallery 0.0.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| zallery-0.0.3.tar.gz | 34.7 kB | Without provenance | Details for zallery-0.0.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| zallery-0.0.3-py3-none-any.whl | Python 3 | none | any | Details for zallery-0.0.3-py3-none-any.whl |
Total release size: 74.0 kB
Release files / zallery-0.0.3.tar.gz
| Download URL | zallery-0.0.3.tar.gz |
|---|---|
| Size | 34.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
63f474c53da08d2bf297ec62c2801f5000da1a5d3a24aeaf8284d5a9eb803cb3
|
|
BLAKE2b-256 checksum How to use checksums |
9020e93224fbef64f3100b1c7c51c89be73d32e989033e00e2970dee5b11c643
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / zallery-0.0.3-py3-none-any.whl
| Download URL | zallery-0.0.3-py3-none-any.whl |
|---|---|
| Size | 39.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
454ab33bc506a04f680e8a2384d78add9241a21b60c704a2fd84334cba10a652
|
|
BLAKE2b-256 checksum How to use checksums |
9b513fb912e8b53b824910ea5f0acd964db632b628c0b5f9060bfe5d2b51b576
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for zallery 0.0.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.