Skip to main content

PyPI version Python versions License

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-run executes nothing, to iterate on prose or layout.
  • --no-cache executes 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.md whose first heading becomes the section title on the index page.
  • An _index.md in 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 thumbnail to use its first image output on the index card.
  • Tag a cell with collapse (or collapse: <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 the example admonition; pick another type with collapse[<type>] or collapse[<type>]: <title>, where <type> is any admonition name Zensical understands (warning, tip, note, ...).
  • 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 with plt.subplots or plt.figure already 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.

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.

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.details and pymdownx.superfences.

  • nav entries 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 thumbnail cell, at <examples>/_assets/default_thumb.svg and <examples>/_assets/default_thumb_dark.svg.

  • Optionally, styles for the classes zallery emits: examples-cards and examples-card-summary on the index page, gallery-output and gallery-rich-output around cell outputs. This repository's zensical.toml and stylesheet are a minimal working setup; the ConfUSIus stylesheet also styles pandas, xarray and scikit-learn outputs.

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.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for zallery 0.0.2
File Size Uploaded Provenance Actions
zallery-0.0.2.tar.gz 29.8 kB Without provenance Details for zallery-0.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for zallery 0.0.2
File Interpreter ABI Platform Actions
zallery-0.0.2-py3-none-any.whl Python 3 none any Details for zallery-0.0.2-py3-none-any.whl

Total release size: 64.3 kB

Release files / zallery-0.0.2.tar.gz

Download URL zallery-0.0.2.tar.gz
Size 29.8 kB
Tags Source
SHA-256 checksum
How to use checksums
2de7c3d5caad792ee1134e7123725ef839f173086567491e9d71603c3b776634
BLAKE2b-256 checksum
How to use checksums
a60107a88f72c0ae1c6d01cb96dc961c1ba890b3a4b194849a5a3eec64daa8c7
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.2-py3-none-any.whl

Download URL zallery-0.0.2-py3-none-any.whl
Size 34.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
02e3e255def250b6d06711792641ba198fa9dd6c230cb29546d43dd4863f9fc8
BLAKE2b-256 checksum
How to use checksums
82c9a211392658a7806ce5d6128dd0ceef3b8b8059310d6f6403a7322280994d
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.2

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page