or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

directives.mdextension-setup.mdindex.mdnotebooks.mdscrapers.mdsorting.mdutilities.md
tile.json

tessl/pypi-sphinx-gallery

A Sphinx extension that builds an HTML gallery of examples from any set of Python scripts.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/sphinx-gallery@0.19.x

To install, run

npx @tessl/cli install tessl/pypi-sphinx-gallery@0.19.0

index.mddocs/

Sphinx-Gallery

A Sphinx extension that automatically builds HTML galleries from collections of Python example scripts, enabling developers to create comprehensive documentation with executable code examples, output displays, and downloadable formats. Sphinx-Gallery provides advanced features including automatic execution of example scripts with output capture, thumbnail generation from matplotlib plots, cross-referencing capabilities, Jupyter notebook conversion, and integration with various visualization libraries.

Package Information

  • Package Name: sphinx-gallery
  • Language: Python
  • Installation: pip install sphinx-gallery
  • Version: 0.19.0

Core Imports

import sphinx_gallery

For extension setup in Sphinx conf.py:

extensions = ['sphinx_gallery.gen_gallery']

For alternative CSS-only setup:

extensions = ['sphinx_gallery.load_style']

Basic Usage

Setting up Sphinx-Gallery in conf.py

# conf.py
extensions = ['sphinx_gallery.gen_gallery']

sphinx_gallery_conf = {
    'examples_dirs': '../examples',   # Source directory for examples
    'gallery_dirs': 'auto_examples',  # Output directory for generated gallery
}

Using RST Directives

In your RST documentation files:

.. minigallery:: numpy.mean
   :add-heading: Examples using ``numpy.mean``

.. image-sg:: /auto_examples/images/plot_example_001.png
   :alt: Example plot
   :srcset: /auto_examples/images/plot_example_001.png, /auto_examples/images/plot_example_001_2x.png 2x

Converting Python Scripts to Jupyter Notebooks

Command line usage:

sphinx_gallery_py2jupyter my_example.py

Programmatic usage:

from sphinx_gallery.notebook import python_to_jupyter

python_to_jupyter(
    'my_example.py',
    'output_notebook.ipynb',
    gallery_conf,
    target_dir
)

Architecture

Sphinx-Gallery follows a modular architecture with several key components:

  • Extension Core: Main setup and configuration handling in gen_gallery module
  • Directives: Custom RST directives for enhanced documentation features
  • Scrapers: Image extraction system supporting matplotlib and custom scrapers
  • Generation Pipeline: Automated RST and HTML generation from Python scripts
  • Notebook Integration: Bidirectional conversion between Python scripts and Jupyter notebooks

The extension integrates deeply with Sphinx's event system and provides hooks for customization at every stage of the gallery generation process.

Capabilities

Extension Setup

Core extension configuration and setup functions for integrating Sphinx-Gallery into Sphinx documentation projects.

def setup(app):
    """
    Main Sphinx extension setup function.
    
    Parameters:
    - app: Sphinx application object
    
    Returns:
    dict: Extension metadata
    """

Extension Setup

RST Directives

Custom RST directives for creating mini-galleries and enhanced image displays in documentation.

class MiniGallery:
    """RST directive for creating mini-galleries of related examples."""
    
class ImageSg:
    """Enhanced image directive with responsive srcset support."""

RST Directives

Image Scrapers

System for extracting and processing images from executed Python code, with built-in matplotlib support and extensible architecture.

def matplotlib_scraper(block, block_vars, gallery_conf, **kwargs):
    """
    Scrapes matplotlib figures from code execution.
    
    Parameters:
    - block: dict, code block information
    - block_vars: dict, execution variables
    - gallery_conf: dict, gallery configuration
    
    Returns:
    list: Image filenames that were saved
    """

Image Scrapers

Gallery Sorting

Flexible sorting system for organizing galleries and examples within galleries.

class ExplicitOrder:
    """Sorting key for explicit ordering of gallery subsections."""
    
    def __init__(self, ordered_list):
        """
        Parameters:
        - ordered_list: list, explicit order of items
        """

Gallery Sorting

Jupyter Notebook Support

Conversion tools and command-line interface for working with Jupyter notebooks.

def python_to_jupyter_cli(args=None, namespace=None, sphinx_gallery_conf=None):
    """
    Command-line interface for converting Python scripts to Jupyter notebooks.
    
    Parameters:
    - args: list, command line arguments
    - namespace: Namespace, parsed arguments
    - sphinx_gallery_conf: dict, gallery configuration
    """

Jupyter Notebook Support

Utilities

Helper functions for image processing, file operations, and common tasks.

def scale_image(in_fname, out_fname, max_width, max_height):
    """
    Scales images while maintaining aspect ratio.
    
    Parameters:
    - in_fname: str, input filename
    - out_fname: str, output filename  
    - max_width: int, maximum width in pixels
    - max_height: int, maximum height in pixels
    """

Utilities

Configuration System

Sphinx-Gallery is configured through the sphinx_gallery_conf dictionary in your Sphinx conf.py file. Key configuration categories include:

Core Gallery Settings

  • examples_dirs: Source directories containing example scripts
  • gallery_dirs: Output directories for generated galleries
  • filename_pattern: Regex pattern for identifying example files
  • plot_gallery: Whether to execute examples during build

Execution Control

  • abort_on_example_error: Stop build on first error
  • expected_failing_examples: List of scripts expected to fail
  • run_stale_examples: Re-run examples when source changes

Output Options

  • download_all_examples: Generate download links for examples
  • thumbnail_size: Dimensions for generated thumbnails
  • show_memory: Display memory usage information
  • show_signature: Include Sphinx-Gallery signature in output

Advanced Configuration

  • image_scrapers: List of functions for extracting images
  • reset_modules: Modules to reset between example executions
  • subsection_order: Function for ordering gallery subsections
  • within_subsection_order: Function for ordering within subsections

Package Metadata

__version__ = "0.19.0"

def glr_path_static():
    """
    Returns path to packaged static files.
    
    Returns:
    str: Absolute path to _static directory
    """

The package provides access to version information and static assets (CSS, JavaScript) for custom integrations.