# sphinx_gallery.gen_rst

reST file generator.

Generate the rst files for the examples by iterating over the python example files.

Files that generate images should start with ‘plot’.

## Functions

sphinx_gallery.gen_rst.codestr2rst(codestr: str, lang: str = 'python', lineno: int | None = None) → str

  Return reStructuredText code block from code string.

sphinx_gallery.gen_rst.executable_script(src_file: str, gallery_conf: dict[str, Any]) → bool

  Validate if script has to be run according to gallery configuration.

  Parameters:

    - src_file (str) – path to python script

    - gallery_conf (dict) – Contains the configuration of Sphinx-Gallery

  Returns:

    True if script has to be executed

  Return type:

    bool

sphinx_gallery.gen_rst.execute_code_block(compiler: Compile, block: Block, example_globals: dict[str, Any] | None, script_vars: dict[str, Any], gallery_conf: dict[str, Any], file_conf: dict[str, Any]) → str

  Execute the code block of the example file.

  Parameters:

    - compiler (codeop.Compile) – Compiler to compile AST of code block.

    - block (sphinx_gallery.py_source_parser.Block) – The code block to be executed.

    - example_globals (Dict[str, Any]) – Global variables for examples.

    - script_vars (Dict[str, Any]) – Configuration and runtime variables.

    - gallery_conf (Dict[str, Any]) – Gallery configurations.

    - file_conf (Dict[str, Any]) – File-specific settings given in source file comments as: `# sphinx_gallery_<name> = <value>`.

  Returns:

    code_output – Output of executing code in reST.

  Return type:

    str

sphinx_gallery.gen_rst.execute_script(script_blocks: list[Block], script_vars: dict[str, Any], gallery_conf: dict[str, Any], file_conf: dict[str, Any]) → tuple[list[str], float]

  Execute and capture output from python script already in block structure.

  Parameters:

    - script_blocks (list) – (label, content, line_number) List where each element is a tuple with the label (‘text’ or ‘code’), the corresponding content string of block and the leading line number

    - script_vars (dict) – Configuration and run time variables

    - gallery_conf (dict) – Contains the configuration of Sphinx-Gallery

    - file_conf (dict) – File-specific settings given in source file comments as: `# sphinx_gallery_<name> = <value>`

  Returns:

    - output_blocks (list) – List of strings where each element is the restructured text representation of the output of each block

    - time_elapsed (float) – Time elapsed during execution

sphinx_gallery.gen_rst.extract_intro_and_title(filename: str, docstring: str) → tuple[str, str]

  Extract and clean the first paragraph of module-level docstring.

sphinx_gallery.gen_rst.generate_dir_rst(src_dir: str, target_dir: str, gallery_conf: dict[str, Any], seen_backrefs: set[str], is_subsection: bool = True) → tuple[str | None, str | None, list[ExampleCost], list[str], dict[str, list[Backreference]]]

  Generate output example reST files for one gallery (sub)directory.

  Parameters:

    - src_dir (str,) – Path to root or sub gallery directory containing example files

    - target_dir (str,) – Path where parsed examples (rst, python files, etc) will be outputted

    - gallery_conf (Dict[str, Any]) – Gallery configurations.

    - seen_backrefs (set,) – Back references encountered when parsing this gallery will be stored in this set.

    - is_subsection (bool,) – Weather src_dir is a subsection dir. If subsection dir, we write a index.rst file with toctree listing every example file. Default=True.

  Returns:

    - index_path (str or None) – Path to index rst file for the src_dir. None if user provided own index.

    - index_content (str or None) – Gallery header content. None when user provided own index.rst.

    - costs (List[ExampleCost]) – List of runtime costs for building each element of the gallery.

    - toctree_items (list,) – List of example file names we generated ReST for.

    - backrefs_dir (dict[str, list[tuple]]) – Dictionary where key is the backreference object name and value is a list of tuples containing: example filename, full path to example source directory, full path to example target directory, intro, title.

sphinx_gallery.gen_rst.generate_file_rst(fname: str, target_dir: str, src_dir: str, gallery_conf: dict[str, Any]) → tuple[str, str, tuple[float, float], dict[str, Any]]

  Generate the rst file for a given example.

  Parameters:

    - fname (str) – Filename of python script.

    - target_dir (str) – Absolute path to directory in documentation where examples are saved.

    - src_dir (str) – Absolute path to directory where source examples are stored.

    - gallery_conf (dict) – Contains the configuration of Sphinx-Gallery.

  Returns:

    - intro (str) – The introduction of the example.

    - title (str) – The example title.

    - cost (tuple) – A tuple containing the `(time_elapsed, memory_used)` required to run the script.

    - out_vars (dict) – Variables used to run the script, possibly with entries:

      ”stale”

        True if the example was stale.

      ”backrefs”

        The backreferences.

      ”passing”

        True if the example passed.

      ”formatted_exception”

        Formatted string of the exception.

sphinx_gallery.gen_rst.handle_exception(exc_info: tuple[type[BaseException], BaseException, Any] | tuple[None, None, None], src_file: str, script_vars: dict[str, Any], gallery_conf: dict[str, Any]) → str

  Trim and format exception, maybe raise error, etc.

sphinx_gallery.gen_rst.md5sum_is_current(src_file: str | Path, mode: Literal['t', 'b'] = 'b') → bool

  Checks whether src_file has the same md5 hash as the one on disk.

sphinx_gallery.gen_rst.patch_warnings() → Any

  Patch warnings.showwarning to actually write out the warning.

sphinx_gallery.gen_rst.rst_blocks(script_blocks: list[Block], output_blocks: list[str], file_conf: dict[str, Any], gallery_conf: dict[str, Any], *, language: str = 'python') → str

  Generate the rst string containing the script prose, code and output.

  Parameters:

    - script_blocks (list) – (label, content, line_number) List where each element is a tuple with the label (‘text’ or ‘code’), the corresponding content string of block and the leading line number

    - output_blocks (list) – List of strings where each element is the restructured text representation of the output of each block

    - file_conf (dict) – File-specific settings given in source file comments as: `# sphinx_gallery_<name> = <value>`

    - language (str) – The language to be used for syntax highlighting in code blocks. Must be a name or alias recognized by Pygments.

    - gallery_conf (dict) – Contains the configuration of Sphinx-Gallery

  Returns:

    out – rst notebook

  Return type:

    str

sphinx_gallery.gen_rst.save_rst_example(example_rst: str, example_file: str | PathLike, time_elapsed: float, memory_used: float, gallery_conf: dict[str, Any], *, language: str = 'python', file_conf: dict[str, Any] | None = None) → None

  Saves the rst notebook to example_file including header & footer.

  Parameters:

    - example_rst (str) – rst containing the executed file content

    - example_file (str | os.PathLike) – Filename with full path of python example file in documentation folder

    - language (str) – Name of the programming language the example is in

    - time_elapsed (float) – Time elapsed in seconds while executing file

    - memory_used (float) – Additional memory used during the run.

    - gallery_conf (dict) – Sphinx-Gallery configuration dictionary

    - file_conf (dict) – The file conf options

sphinx_gallery.gen_rst.save_thumbnail(image_path_template: str, src_file: str, script_vars: dict[str, Any], file_conf: dict[str, Any], gallery_conf: dict[str, Any]) → None

  Generate and Save the thumbnail image.

  Parameters:

    - image_path_template (str) – holds the template where to save and how to name the image

    - src_file (str) – path to source python file

    - script_vars (dict) – Configuration and run time variables

    - file_conf (dict) – File-specific settings given in source file comments as: `# sphinx_gallery_<name> = <value>`

    - gallery_conf (dict) – Sphinx-Gallery configuration dictionary

## Classes

class sphinx_gallery.gen_rst.ExampleCost(execution_time: float, memory: float, src_file: str, target_dir: str)

  Runtime cost of a single example script.

  execution_time

    Execution time in seconds.

    Type:

      float

  memory

    Peak memory usage in MB.

    Type:

      float

  src_file

    Path to the source Python file.

    Type:

      str

  target_dir

    Path to the target output directory.

    Type:

      str

  sort_key() → tuple[float, float, str]

    Return sort key for consistent ordering.

    Returns tuple of: descending time, descending memory, ascending filename. This orders examples to show the most expensive/problematic ones first.