Structuring Python scripts for Sphinx-Gallery#

This page describes the structure and syntax that can be used in Python scriptsto generate rendered HTML gallery pages.

A simple example#

Sphinx-Gallery expects each Python file to have two things:

  1. A docstring, written in reST, that defines theheader for the example. It must begin by defining a reST title. The titlemay contain any punctuation mark but cannot start with the same punctuationmark repeated more than 3 times. For example:

    """"This" is my example-script===========================This example doesn't do much, it just makes a simple plot"""
  2. Python code. This can be any valid Python code that you wish. AnyMatplotlib images that are generated will be saved to disk, andthe reST generated will display these images with the built examples. Bydefault only images generated by Matplotlib, or packages based on Matplotlib(e.g., Seaborn or Yellowbrick) are saved and displayed. However, you canchange this to include other packages, seeImage scrapers.

For a quick reference have a look at the exampleIntroductory example - Plotting sin

Embed reST in your example Python files#

Additionally, you may embed reST syntax within your Python scripts. reSTallows you to easily add formatted text, math equations and reference links,includingcross referencing other examples. Thiswill be rendered in-line with the Python code and its outputs, similar to howJupyter Notebooks are structured (in fact, Sphinx-Gallery alsocreates aJupyter Notebook for each example that is built).

You can embed reST in your Python examples by including a line of >= 20#symbols,#%%, or#%%. For consistency, it is recommended that you useonly one of the above three ‘block splitter’ options in your project. If usinga line of#’s, we recommend using 79#’s, like this:

###############################################################################

Any commented lines (line beginning with# followed by a space, tobe PEP8-compliant) that immediately follow a block splitter will be rendered asreST in the built gallery examples. To switch back to writing code, eitherstop starting lines with# and a space or leave an empty line before writingcode comments. You can thus easily alternate between text and code ‘blocks’.For example:

# This is commented pythonmyvariable=2print("my variable is{}".format(myvariable))# %%# This is a section header# ------------------------## In the built documentation, it will be rendered as reST. All reST lines# must begin with '# ' (note the space) including underlines below section# headers.# These lines won't be rendered as reST because there is a gap after the last# commented reST block. Instead, they'll resolve as regular Python comments.# Normal Python code can follow these comments.print('my variable plus 2 is{}'.format(myvariable+2))

The#%% and#%% syntax is consistent with the ‘code block’ (or‘code cell’) separator syntax inVisual Studio Code Python extension,Visual Studio Python Tools,Jupytext,Pycharm Professional,Hydrogen plugin (for Atom)andSpyder.Note that although the documentation of these editors/IDEsmay only mention one of#%% or#%%, in practice bothwork. With these editors/IDEs,#%% or#%% at the start of a line signifies the start of a new code block.Code blocks allow you to separate your code into chunks, like in JupyterNotebooks. All the code within a code block can be easily executed together.This functionality can be helpful when writing a Sphinx-Gallery.pyexample asthe blocks allow you to easily create pairs of subsequent Sphinx-Gallery textand code blocks.

Here are the contents of an example Python file using the ‘code block’functionality:

"""This is my example script=========================This example doesn't do much, it just makes a simple plot"""# %%# This is a section header# ------------------------# This is the first section!# The `#%%` signifies to Sphinx-Gallery that this text should be rendered as# reST and if using one of the above IDE/plugin's, also signifies the start of a# 'code block'.# This line won't be rendered as reST because there's a space after the last block.myvariable=2print("my variable is{}".format(myvariable))# This is the end of the 'code block' (if using an above IDE). All code within# this block can be easily executed all at once.# %%# This is another section header# ------------------------------## In the built documentation, it will be rendered as reST after the code above!# This is also another code block.print('my variable plus 2 is{}'.format(myvariable+2))

For a clear example refer to the rendered exampleAlternating text and code and compare it to the generatedoriginalpythonscript

Examples in other programming languages#

Sphinx-Gallery also supports rendering HTML pages for examples written in programminglanguages other than Python, although these examples are not currently executed orscanned for output. Seefilename/ignore patterns forconfiguration settings.

For such examples, the header for the example is defined by the first comment block inthe file, which must contain a reST title, and may contain any additional reST contentthat should appear above the first code block. For example, a C++ example could startwith:

// My Awesome Example// ==================//// The description continues as long as there are lines// that start with a comment character.

reST content can likewise be embedded in comments that are marked with a specialdelimiter, where that delimiter depends on the comment characters used by the languageof the example. Valid special delimiters are:

  1. The comment character followed by%%. For example//%% for C++.

  2. The comment character followed by a space, followed by%%. For example,//%%for C++.

  3. A line of at least 20 comment characters. For example,//////////////////// forC++.

Any text following the special delimiter on the same line will be converted into a reSTheading (underlined with-). The reST block continues until a line that does notstart with a comment character is encountered. Some examples:

// %% Important Heading// This is some text in a reST block in C++, appearing underneath a heading.//// * Start a list// * Check it twice
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! This is the start of a reST block in Fortran 90.!! It can contain multiple paragraphs.

For languages that use C-style multiline comments, the following styles are supported:

/* %% * Subheading * ---------- * * Description */inty=3;/**************************//* Another subheading     *//* ------------------     *//*                        *//* Description            *//**************************/doublez=1.5;

Finally, for compatibility with Matlab’s use of a simple%% delimiter to mark codesections, this is allowed as a special delimiter in Matlab source files, in addition tothe multi-language syntax described above:

%% Heading% some text below the heading

Plain reST examples#

Sphinx-Gallery can also generate gallery pages from plain reStructuredTextfiles. Place .rst files in your example folder and include ‘.rst’ in theexample_extensions config, e.g.

sphinx_gallery_conf={...'example_extensions':{'.py','.rst'}}

Because Sphinx-Gallery copies the .rst files as-is, no code is executed,and no .py and notebook downloads are available.

Tip

If you want classes and functions in reST code blocks to become hyperlinksto their documentation, you might findsphinx-codeautolinkhelpful.