Configuration#

Configuration and customization of Sphinx-Gallery is done primarily with adictionary specified in yourconf.py file. A list of the possiblekeys are listedbelow and explained ingreater detail in subsequent sections.

When using these flags, it is good practice to make sure the source Python filesare equivalent to the generated HTML and iPython notebooks (i.e. make sure.py==.html==.ipynb). This principle should be violated only whennecessary, and on a case-by-case basis.

Configuration options#

Globalconf.py configurations#

Sphinx-Gallery configuration options that can be set in the Sphinxconf.pyfile, inside asphinx_gallery_conf dictionary.

Gallery files and ordering

Example execution

Diverging from Jupyter

Sphinx-gallery attempts to render examples to HTML in a manner largely consistent with what a user will experience when they download the corresponding.ipynb notebook file and run it locally.Some options, such as'capture_repr':(),, will make these behaviors less consistent.Consider using these options sparingly as it could lead to confusion or sub-optimal experiences for users!

Cross-referencing

Images and thumbnails

Compute costs

Jupyter notebooks and interactivity

Appearance

Miscellaneous

Configurations inside examples#

Some options can also be set or overridden on a file-by-file basis:

Some options can be set on a per-code-block basis in a file:

Some options can be set on a per-line basis in a file:-#sphinx_gallery_start_ignore and#sphinx_gallery_end_ignore (Hiding lines of code)

See alsoRemoving config comments to hide config comments in files fromthe rendered examples.

Build options#

Configuration options can be set at build time via theSphinx build -Dcommand line option. This overrides the value set in yourconf.py file for thatconfiguration. Values set in yourconf.py are effectively the ‘default’,as it takes lower precedence than values passed via the-D build option.

You can also use the-D option in your Makefile to create useful targets,for example:

Note

If you wish to use the-D build option to pass an instantiated class, class orfunction as a configuration value, you can do so by passing a fully qualified namestring to the object. SeeImporting callables for details.

CSS changes#

Some things can be tweaked directly in CSS:

Removing warnings#

To prevent warnings from being captured and included in your builtdocumentation, you can use the packagewarnings in theconf.py file.For example, to remove the specific Matplotlib agg warning, you can add:

importwarningswarnings.filterwarnings("ignore",category=UserWarning,message='Matplotlib is currently using agg, which is a'' non-GUI backend, so cannot show the figure.''|(\n|.)*is non-interactive, and thus cannot be shown')

to yourconf.py file.

Note that the above Matplotlib warning is removed by default.

Importing callables#

Sphinx-Gallery configuration values that are instantiated classes, classesor functions should be passed as fully qualified name strings to the objects.The object needs to be importable by Sphinx-Gallery.

Two common ways to achieve this are:

  1. Define your object with your package. For example, you could write a functiondefmy_sorter and put it inmymod/utils.py, then use:

    sphinx_gallery_conf={#...,"minigallery_sort_order":"mymod.utils.my_sorter",#...}
  2. Define your object with your documentation. For example,you can add documentation-specific stuff in a different path and ensurethat it can be resolved at build time. For example, you could create a filedoc/sphinxext.py and define your function:

    defplotted_sorter(fname):returnnotfname.startswith("plot_"),fname

    And set in your configuration:

    sys.path.insert(0,os.path.dirname(__file__))sphinx_gallery_conf={#...,"minigallery_sort_order":"sphinxext.plotted_sorter",#...}

    And Sphinx-Gallery would resolve"sphinxext.plotted_sorter" to theplotted_sorter object because thedoc/ directory is first on the path.

Built in classes likesphinx_gallery.sorting.FileNameSortKey and similar canbe used with shorter direct alias strings like"FileNameSortKey" (seeSorting gallery examples for details).

Note

Sphinx-Gallery >0.16.0 supports use of fully qualified name strings as a responseto the Sphinx >7.3.0 changes to caching and serialization checks of theconf.py file.

This means that the previous use of class instances as configuration values toensure the__repr__ was stable across builds is redundantif you are passingconfiguration values via name strings. When using name strings, the configurationobject can just be a function.

Custom sort keys#

You can create a custom sort key callable for the following configurations:

The best way to do this is to define a sort function, that takes the passed pathstring. For example, this function puts all filenames starting withplot_ beforeall other filenames:

defplotted_sorter(fname):return(notfname.startswith("plot_"),fname)

Then make sure it is importable (seeImporting callables) and set yourconfiguration:

sphinx_gallery_conf={#...,"minigallery_sort_order":"sphinxext.plotted_sorter",#...}

For backwards compatibility you can also set your configuration to be a callableobject but you will have to ensure that the__repr__ is stable across runs.SeeEnsuring a stable __repr__ for details.

If you do this, we recommend that you use thesphinx_gallery.sorting.FunctionSortKeybecause it will ensure that the__repr__ is stable across runs.

sphinx_gallery.sorting.FunctionSortKey takes a function on init.You can create your sort key callable by instantiating aFunctionSortKey instance with your sort keyfunction. For example, the followingminigallery_sort_order configuration(which sorts on paths) will sort using the first 10 letters of each filename:

sphinx_gallery_conf={#...,"minigallery_sort_order":FunctionSortKey(lambdafilename:filename[:10]),#...}

Ensuring a stable__repr__#

For backwards compatibility Sphinx-Gallery allows certain configuration values to bea callable object instead of aimportable name string.

If you wish to use a callable object you will have to ensure that the__repr__is stable across runs. Sphinx determines if the build environment haschanged, and thus ifall documents should be rewritten, by examining theconfig values usingmd5(str(obj).encode()).hexdigest() insphinx/builders/html.py. Default class instances in Python have theirmemory address in their__repr__ which is why generally the__repr__changes in each build.

Your callable should be a class that defines a stable__repr__ method.For example,sphinx_gallery.sorting.ExplicitOrder stability isensured via the custom__repr__:

def__repr__(self):return'<%s:%s>'%(self.__class__.__name__,self.ordered_list)

Therefore, the files are only all rebuilt when the specified ordered listis changed.

Manage multiple galleries#

To specify the locations of your input and output gallery folder(s), use the followingSphinx-Gallery configuration dictionary keys:

  • examples_dirs (folder where source example files are)

  • gallery_dirs (folder where output files should be placed)

Both configurations take list of directory paths, relative to theconf.py file.They can be set in your Sphinxconf.py file:

sphinx_gallery_conf={...'examples_dirs':['../examples','../tutorials'],'gallery_dirs':['auto_examples','tutorials'],}

Keep in mind that both lists should be of the same length.

Each folder inexamples_dirs will be built into an examples gallery. Subfolderswithin eachexamples_dirs will be built into gallery subsections (sub-galleries)of the parent gallery.

Sphinx-Gallery only supports one level of subfolder nesting in its gallery directories.For example ourBasics Gallery with Matplotlib, has the parent gallery inexamples/ andthe subsection (aka sub-gallery) inexamples/no_output/. Further sub-folders arenot supported. This might be a limitation for you, or you might want to have separategalleries for different purposes, e.g., an examples gallery and a tutorials gallery.

Note

If your examples take a long time to run, consider looking at theexecution timesfile that is generated for each gallery dir (as long as any exampleswere actually executed in that directory during the build)and globally for all galleries.

Parsing and executing examples via matching patterns#

By default, Sphinx-Gallery willparse and add all files with a.pyextension to the gallery, but onlyexecute files beginning withplot_.These behaviors are controlled by theignore_pattern,filename_pattern,andexample_extensions entries, which have the default values:

sphinx_gallery_conf={...'filename_pattern':'/plot_','ignore_pattern':r'__init__\.py','example_extensions':{'.py'}}

To omit some files from the gallery entirely (i.e., not execute, parse, oradd them), you can change theignore_pattern option.To choose which of the parsed and added Python scripts are actuallyexecuted, you can modifyfilename_pattern. For example:

sphinx_gallery_conf={...'filename_pattern':'/plot_compute_',}

will build all examples starting withplot_compute_. The keyfilename_pattern (andignore_pattern) acceptsregular expressionswhich will be matched with the full path of the example. This is the reasonthe leading'/' is required. Users are advised to usere.escape(os.sep)instead of'/' if they want to be agnostic to the operating system.

Thefilename_pattern option is also useful if you want to build only asubset of the examples. For example, you maywant to build only one example so that you can link it in the documentation.In that case, you would do:

sphinx_gallery_conf={...'filename_pattern':r'plot_awesome_example\.py',}

Here, one should escape the dotr'\.' as otherwise pythonregular expressions matches any character. Nevertheless, asone is targeting a specific file, it would match the dot in the filename evenwithout this escape character.

Note

Sphinx-Gallery only re-runs examples that have changed (according to theirmd5 hash). SeeRerunning stale examples below for information.

Similarly, to build only examples in a specific directory, you can do:

sphinx_gallery_conf={...'filename_pattern':'/directory/plot_',}

Alternatively, you can skip executing some examples. For example, to skipbuilding examples starting withplot_long_examples_, you would do:

sphinx_gallery_conf={...'filename_pattern':'/plot_(?!long_examples)',}

As the patterns are parsed asregular expressions, users are advised toconsult theregular expressions module for more details.

Note

Remember that Sphinx allows overridingconf.py values from the commandline, so you can for example build a single example directly via somethinglike:

$sphinx-build-Dsphinx_gallery_conf.filename_pattern=plot_specific_example\.py...

You can also parse and highlight syntax examples in other languages by adding theirextensions toexample_extensions, though they will not be executed. For example, toinclude examples in Python, Julia, and C++:

sphinx_gallery_conf={...'example_extensions':{'.py','.jl','.cpp'}}

Parsing and syntax highlighting is supported by the Pygments library, with the languagedetermined by the file extension. To override Pygments’ default file associations, thefiletype_parsers option can be used to specify adict mapping any of the fileextensions inexample_extensions to any of thepygments language names. For example:

sphinx_gallery_conf={...'filetype_parsers':{'.m':'Matlab'}}

Rerunning stale examples#

By default, Sphinx-Gallery only rebuilds examples that have changed.For example, when starting from a cleandoc/ directory, running your HTMLbuild once will result in Sphinx-Gallery executing all examples that match yourgivenfilename/ignore patterns. Then, runningthe exact same command a second timeshould not run any examples, because theMD5 hash of each example will be checked against the MD5 hash (saved to diskas<filename>.md5 in the generated directory) that the example file hadduring the first build. These will match and thus the example will bedetermined to be “stale”, and it will not be rebuilt by Sphinx-Gallery.This design feature allows for more rapid documentation iteration by onlyrebuilding examples when they change.

However, this presents a problem during some modes of debugging anditeration. Let’s say that you have one particularexample that you want to rebuild repeatedly while modifying some function inyour underlying library but do not want to change the example file contentsthemselves. To do this, you’d either need to make some change (e.g., add/deletea newline) to your example or delete the.md5 file to force Sphinx-Galleryto rebuild the example. Instead, you can use the configuration value:

sphinx_gallery_conf=={...'run_stale_examples':True,}

With this configuration, all examples matching the filename/ignore pattern willbe rebuilt, even if their MD5 hash shows that the example did not change.You can combine this withfilename/ignore patternsto repeatedly rerun a single example.This could be done from the command line, for example:

$makehtmlSPHINXOPTS="-D sphinx_gallery_conf.run_stale_examples=True -D sphinx_gallery_conf.filename_pattern='my_example_name'"

This command will cause any examples matching the filename pattern'my_example_name' to be rebuilt, regardless of their MD5 hashes.

Passing command line arguments to example scripts#

By default, Sphinx-Gallery will not pass any command line arguments to examplescripts. By setting thereset_argv option, it is possible to change thisbehavior and pass command line arguments to example scripts.reset_argvneeds to be aCallable that accepts thegallery_conf andscript_varsdictionaries as input and returns a list of strings that are passed asadditional command line arguments to the interpreter.

Areset_argv example could be:

frompathlibimportPathdefreset_argv(sphinx_gallery_conf,script_vars):src_file=Path(script_vars['src_file']).nameifsrc_file=='example1.py':return['-a','1']elifsrc_file=='example2.py':return['-a','2']else:return[]

This function is defined indoc/sphinxext.py and we ensured that it is importable(seeImporting callables).

This can be included in the configuration dictionary as:

sphinx_gallery_conf={...'reset_argv':"sphinxext.reset_argv",}

which is then resolved by Sphinx-Gallery to the callablereset_argv and used as:

importsyssys.argv[0]=script_vars['src_file']sys.argv[1:]=reset_argv(gallery_conf,script_vars)

Note

For backwards compatibility you can also set your configuration to be a callableobject but you will have to ensure that the__repr__ is stable across runs.SeeEnsuring a stable __repr__.

Sorting gallery subsections#

Gallery subsections (aka sub-galleries) are sorted by default alphabetically bytheir folder name, and as such you can always organize them by changing your foldernames. Alternatively, you can specify the order via the config valuesubsection_order by providing a list of the subsections as pathsrelative toconf.py in the desired order:

sphinx_gallery_conf={...'examples_dirs':['../examples','../tutorials'],'subsection_order':['../examples/sin_func','../examples/no_output','../tutorials/seaborn'],}

Here we build 2 main galleriesexamples andtutorials, each of themwith subsections. You must list all subsections. If that’s too cumbersome,one entry can be “*”, which will collect all not-listed subsections, e.g.["first_subsection","*","last_subsection"].

Even more generally, you can setsubsection_order to any callable, whichwill be used as the sorting key function on the subsection folder paths (relativeto theconf.py file). SeeCustom sort keys for more information.

In fact, theabove list is a convenience shortcut and it is internally wrapped insphinx_gallery.sorting.ExplicitOrder as a sortkey.

Note

Sphinx-Gallery <0.16.0 required to wrap the list inExplicitOrder

fromsphinx_gallery.sortingimportExplicitOrdersphinx_gallery_conf={...'subsection_order':ExplicitOrder([...])}

This pattern is discouraged in favor of passing the simple list.

Keep in mind that we use a single sort keyfor all the galleries that are built, thus we include the prefix of eachgallery in the corresponding subsection folders. One does not define asortkey per gallery. You can use Linux paths, and if your documentation isbuilt in a Windows system, paths will be transformed to work accordingly,the converse does not hold.

Sorting gallery examples#

Within a given gallery (sub)section, the example files are ordered byusing the standardsorted() function with thekey argument by defaultset toNumberOfCodeLinesSortKey(src_dir),which sorts the files based on the number of code lines:

sphinx_gallery_conf={...'within_subsection_order':"NumberOfCodeLinesSortKey",}

Built in convenience classes supported bywithin_subsection_order:

These built in Sphinx-Gallery classes can be specified using just the classname asa string, e.g.,"FileSizeSortKey". It is functionally equivalent to providing thefully qualified name string"sphinx_gallery.sorting.NumberOfCodeLinesSortKey"or importing and passing the class. SeeImporting callables for details.

You can also pass your own custom sort key callable, which will be used to sortthe full paths to example files in the (sub)section. SeeCustom sort keys formore information.

Note

For backwards compatibility,within_subsection_order can also be aclass, which will be instantiated with the full path to the output directory;gallery_dir.

Add intersphinx links to your examples#

Sphinx-Gallery enables you to add hyperlinks to thecode blocks in your examplefiles. This links functions/methods/attributes/objects/classes used, to their matchingonline documentation.

Such code snippets within the gallery appear like this:

y=np.sin(x)

Note

Sphinx-Gallery does not manage hyperlinks in reSTtext blocks. Thesedepend on your Sphinx setup. If your project usessphinx.ext.intersphinx,hyperlinks to external modules will be added to text blocks, similar to a normalSphinx reST documentation file.

If you use the Sphinx extensionsphinx.ext.intersphinx, entries intheintersphinx inventory will automatically be used for linking insidecode blocks. If you wish to add or over-ride anyintersphinx module, you canuse the Sphinx-Galleryreference_url configuration.reference_url accepts a dictionary where the key is the module name string andvalue is the URL to the module’s documentation directory page, containingsearchindex.js, such as'matplotlib':'https://matplotlib.org'.

To link the local module, useNone as the value, as shown below:

sphinx_gallery_conf={...'reference_url':{# The module you locally document uses None'sphinx_gallery':None,}}

To add links to code blocks in plain reST example files inside galleries,seePlain reST examples.

Have a look at this functionality in full actionin our exampleIntroductory example - Plotting sin.

Resolving module paths#

When finding links to objects we use, by default, the shortest module path,checking that it still directs to the same object. This is because it is commonfor a class that is defined in a deeper module to be documented in a shallowerone because it is imported in a higher level modules’__init__.py (thusthat’s the namespace users expect it to be).

However, if you are using inherited classes in your code and are experiencingincorrect links in the sense that links point to the base class of an objectinstead of the child, the optionprefer_full_module might solve your issue.Seethe GitHubissuefor more context.

To make this work in your documentation you need to includeprefer_full_module in the Sphinx-Gallery configuration dictionary inconf.py:

sphinx_gallery_conf={...# Regexes to match the fully qualified names of objects where the full# module name should be used. To use full names for all objects use: '.*''prefer_full_module':{r'module\.submodule'}}

In the above example, all fully qualified names matching the regex'module\.submodule' would use the full module name(e.g., module.submodule.meth) when creating links, instead of the short modulename (e.g., module.meth). All others will use the (default) way of linking.

Add mini-galleries#

Sphinx-Gallery provides thesphinx_gallery.directives.MiniGallerydirective so that you can easily add a gallery of specific examples,a ‘mini-gallery’, to your reST. This directive works in both reST text blocks inexamples and.rst files.

The minigallery directive supports passing a list, as a space separated directiveargument or in the body of the directive. There are two ways to specify examplesto include in the mini-gallery:

To use object names, you must enable backreference generation, seeAdd mini-galleries for API documentation for details.If backreference generation is not enabled, object entries to theMiniGallery directive will be ignoredand all entries will be treated as pathlike strings or glob-style pathlike strings.SeeCreate mini-galleries using file paths for details.

For example, the reST below will add a mini-gallery that includes allexamples that use or reference the specific functionnumpy.exp, the exampleexamples/plot_sin_.py, and all example files matching the string/examples/plot_4*:

..minigallery:: numpy.exp ../examples/plot_0_sin.py ../examples/plot_4*

All relevant examples will be merged into a single mini-gallery. Themini-gallery will only be shown if the files exist or the items are actuallyused or referred to in an example. Sphinx-Gallery will prevent duplication, ensuringthat examples ‘passed’ more than once (e.g., one example uses a passed objectandmatches a passed file string) will only appear once in the mini-gallery.

You can also sort the examples in your mini-galleries. SeeSort mini-gallery thumbnails from filesfor details.

The mini-gallery directive also supports the following options:

  • add-heading - adds a heading to the mini-gallery.

    • The default heading for a mini-gallery with a single passed argument is:“Examples using{full qualified object name}”.

    • The default heading for a mini-gallery with multiple passed arguments is:“Examples of one of multiple objects”.

  • heading-level - specify the heading level. Accepts a single character(e.g.,-).

For example, the following reST adds the heading “My examples”, with headinglevel-. It also shows how to pass inputs in the body of the directive (instead ofas directive arguments).

..minigallery:::add-heading: My examples:heading-level: -    numpy.exp    ../examples/plot_0_sin.py    ../examples/plot_4*

Add mini-galleries for API documentation#

Sphinx-Gallery can generate minigalleries for objects from specified modules,consisting of all examples that either:

  1. Use the function/method/attribute/object or instantiate the class in thecode (calledimplicit backreferences) or

  2. Refer to that function/method/attribute/object/class using sphinx markup:func: /:meth: /:attr: /:obj: /:class: in a textblock. You can omit this role markup if you have set thedefault_rolein yourconf.py to any of these roles (calledexplicitbackreferences).

This allows you to pass a fully qualified name of an object (e.g., function, method,attribute, class) to the minigallery directive to add a minigallery of all examplesrelevant to that object. This can be useful in API documentation.

Implicit backreferences are useful for auto-documenting objectsthat are used and classes that are explicitly instantiated, in the code. Any exampleswhere an object is used in the code are addedimplicitly as backreferences.

Explicit backreferences are for objects that areexplicitly referred toin an example’s text. They are useful for classes that aretypically implicitly returned in the code rather than explicitly instantiated (e.g.,matplotlib.axes.Axes which is most often instantiated only indirectlywithin function calls).

For example, we can embed a small gallery of all examples that use orrefer tonumpy.exp, which looks like this:

Examples usingnumpy.exp#

Plotting the exponential function

Plotting the exponential function

Choosing the thumbnail figure

Choosing the thumbnail figure

Identifying function names in a script

Identifying function names in a script

For such behavior to be available, set the following Sphinx-Gallery configurationsin yourconf.py file:

Required

  • backreferences_dir - directory where object granular galleries are stored.

    • This should be a string orpathlib.Path object that isrelative to theconf.py file, orNone.

    • It isNone by default, which means thatbackrefererences are not generated.

  • doc_module - the modules for which you want object level galleriesto be created.

    • It should be a tuple of string module names.

Optional

  • exclude_implicit_doc - Regexes to match objects to exclude from implicitbackreferences, as set of string regexes.

For example:

sphinx_gallery_conf={...# directory where function/class granular galleries are stored'backreferences_dir':'gen_modules/backreferences',# here we want to create backreferences for sphinx_gallery and numpy'doc_module':('sphinx_gallery','numpy'),# Regexes to match objects to exclude from implicit backreferences.'exclude_implicit_doc':{r'pyplot\.show'},}

The path you specify inbackreferences_dir (here we choosegen_modules/backreferences) will be populated with a file called“backreferences_all.json”. This contains a mapping of all of all objectsbelonging to the modules listed indoc_module and not excluded inexclude_implicit_doc, to the examples where it was used or referenced.Objects not used or referenced in any example are not included.

For backwards compatibilitybackreferences_dir will also be populated withreST files for each object, named ‘<object>.examples’.Each .rst file will contain a reduced version of thegallery, containing examples where that “object” that is used.‘<object>.examples’ files will be generated for all objects to prevent inclusionerrors. Empty ‘<object>.examples’ files are created for objects not used in anyexample.

exclude_implicit_doc#

Sometimes, there are functions that are being used in practically every examplefor the given module, for instance thepyplot.show orpyplot.subplotsfunctions in Matplotlib, so that a large number of often spurious examples willbe linked to these functions. To prevent this, you can exclude implicitbackreferences for certain objects by including them as regular expressionsinexclude_implicit_doc. The following setting will exclude any implicitbackreferences so that examples galleries are only created for objectsexplicitly mentioned by Sphinx markup in a documentation block:{'.*'}.To exclude the functions mentioned above you would use{r'pyplot\.show',r'pyplot\.subplots'} (note the escape to match a dotinstead of any character, if the name is unambiguous you can also writepyplot.show or justshow).

Create mini-galleries using file paths#

Sometimes you may want to explicitly create amini-gallery using files thatdo not have functions in common, for example a set of tutorials. Themini-gallery directive therefore also supports passing in:

  • pathlike strings to sphinx gallery example files (relative toconf.py)

  • glob-style pathlike strings to Sphinx-Gallery example files (relative toconf.py).For example, passing/examples/plot_4* will include all example filesmatching the above pattern.

Sort mini-gallery thumbnails from files#

Theminigallery directive generates a gallery ofthumbnails corresponding to the input file strings or object names.You can specify minigallery thumbnails order via theminigallery_sort_orderconfiguration, which gets passed to thesorted()key parameter whensorting all minigalleries.

Sorting is done on the full paths to all the gallery examples (e.g.,path/to/plot_example.py) that correspond to the inputs.

SeeCustom sort keys for details on writing a custom sort key.

For example, to put all example thumbnails starting with"plot_numpy_" at the start,we could define the function below indoc/sphinxext.py (noteFalse gets sortedahead ofTrue as 0 is less than 1):

deffunction_sorter(x)return(notPath(x).name.starts_with("plot_numpy_"),x)::

We can then set the configuration to be (ensuring the function isimportable):

sphinx_gallery_conf={#...,"minigallery_sort_order":"sphinxext.function_sorter",#...}

Sphinx-Gallery would resolve"sphinxext.function_sorter" to thefunction_sorter object.

Note that you can only define one sorting key for all minigalleries.

Auto-documenting your API with links to examples#

The previous feature can be automated for all your modules combiningit with the standard sphinx extensionsautodoc andautosummary.First enable them in yourconf.py extensions list:

importsphinx_galleryextensions=[...'sphinx.ext.autodoc','sphinx.ext.autosummary','sphinx_gallery.gen_gallery',]# generate autosummary even if no referencesautosummary_generate=True

autodoc andautosummaryare very powerful extensions, please read about them. In this example we’llexplain how theSphinx-Gallery API Reference is automatically generated. Thedocumentation is done at the module level. We first start with thereference.rst file

.._sphx_glr_api_reference:Sphinx-Gallery API Reference============================..note::   Sphinx-Gallery is typically used indirectly via Sphinx execution and   configuration variables, see:ref:`configuration` for how to do this.   However, as a standard  Python project, we document many functions and   classes as well below, even though these will typically not be needed   by end users...currentmodule:: sphinx_gallery..automodule:: sphinx_gallery:no-members::no-inherited-members::py:mod:`sphinx_gallery`:..autosummary:::toctree: gen_modules/:template: module.rst   gen_gallery   backreferences   gen_rst   scrapers   py_source_parser   block_parser   docs_resolv   notebook   downloads   sorting   interactive_example   directives..currentmodule:: sphinx_gallery.utils..automodule:: sphinx_gallery.utils:no-members::no-inherited-members::py:mod:`sphinx_gallery.utils`:..autosummary:::toctree: gen_modules/:template: module.rst   optipng

The important directives arecurrentmodule where we specify whichmodule we are documenting, for our purpose issphinx_gallery. Theautosummary directive is responsible for generating therstfiles documenting each module.autosummary takes the optiontoctree which is where therst files are saved andtemplatewhich is the file that describes how the modulerst documentationfile is to be constructed, finally we write the modules we wish todocument, in this case all modules of Sphinx-Gallery.

The template filemodule.rst for theautosummary directive hasto be saved in the path_templates/module.rst. We present ourconfiguration in the following block. The most relevant part is theloop defined between lines12-21 that parses all the functions/classesof the module. There we have used theminigallery directive introduced inthe previous section.

We also add a cross referencing label (on line 16) before including theexamples mini-gallery. This enables you to reference the mini-gallery forall functions/classes of the module using:ref:`sphx_glr_backref_<fun/class>`, where ‘<fun/class>’ is the full pathto the function/class using dot notation (e.g.,sphinx_gallery.backreferences.identify_names). For example, see:Examples using sphinx_gallery.backreferences.identify_names.

 1{{ fullname }} 2{{ underline }} 3 4..automodule:: {{ fullname }} 5 6   {% block functions %} 7   {% if functions %} 8 9   Functions10   ---------1112   {% for item in functions %}1314   ..autofunction:: {{ item }}1516   .._sphx_glr_backref_{{fullname}}.{{item}}:1718   ..minigallery:: {{fullname}}.{{item}}19:add-heading:2021   {%- endfor %}22   {% endif %}23   {% endblock %}2425   {% block classes %}26   {% if classes %}2728   Classes29   -------3031   {% for item in classes %}32   ..autoclass:: {{ item }}33:members:3435   .._sphx_glr_backref_{{fullname}}.{{item}}:3637   ..minigallery:: {{fullname}}.{{item}}38:add-heading:3940   {%- endfor %}41   {% endif %}42   {% endblock %}4344   {% block exceptions %}45   {% if exceptions %}4647   Exceptions48   ----------4950   ..autosummary::51   {% for item in exceptions %}52      {{ item }}53   {%- endfor %}54   {% endif %}55   {% endblock %}

Toggling global variable inspection#

By default, Sphinx-Gallery will inspect global variables (and code objects)at the end of each code block to try to find classes of variables andmethod calls. It also tries to find methods called on classes.For example, this code:

lst=[1,2]fig,ax=plt.subplots()ax.plot(lst)

should end up with the following links (assuming intersphinx is set upproperly):

However, this feature might not work properly in all instances.Moreover, if variable names get reused in the same script to refer todifferent classes, it will break.

To disable this global variable introspection, you can use the configurationkey:

sphinx_gallery_conf={...'inspect_global_variables':False,}

Stylizing code links using CSS#

Each link in the code blocks will be decorated with two or three CSS classes.

  1. sphx-glr-backref-module-*

    CSS class named after the module where the object is documented.* represents the module, e.g.,sphx-glr-backref-module-matplotlib-figure.

  2. sphx-glr-backref-type-*

    CSS class named after the type of the object, where* representsthe object type. This is a sanitized intersphinx type, e.g., apy:class will have the CSS classsphx-glr-backref-type-py-class.

  3. sphx-glr-backref-instance

    The third ‘optional’ class that is added only if the object is aninstance of a class (rather than, e.g., a class itself, method, orfunction). By default, Sphinx-Gallery adds the following CSS ingallery.css:

    a.sphx-glr-backref-instance{text-decoration:none;}

    This is done to reduce the visual impact of instance linkingin example code. This means that for the following code:

    x=Figure()

    x, an instance of a class, will have thesphx-glr-backref-instance CSS class, and will not be decorated.Figure however, is a class, so will not have thesphx-glr-backref-instance CSS class, and will thus be decorated thestandard way for links in the given parent styles.

These three CSS classes are meant to give fine-grained control over howdifferent links are decorated. For example, using CSS selectors you couldchoose to avoid highlighting anysphx-glr-backref-* links except for onesthat you allowlist (e.g., those from your own module). For example, thefollowing css prevents any module except for matplotlib from being decorated:

a[class^="sphx-glr-backref-module-"]{text-decoration:none;color:inherit;}a[class^="sphx-glr-backref-module-matplotlib"]{text-decoration:underline;}

There are likely elements other thantext-decoration that might be worthsetting, as well.

You can add these CSS classes by including your own CSS file via the Sphinxconfigurationhtml_static_path, which will override thedefault CSS classes inSphinx-Gallery CSS files.

Using a custom default thumbnail#

In case you want to use your own image for the thumbnail of examples that donot generate any plot, you can specify it by editing your Sphinxconf.pyfile. You need to add to the configuration dictionary a key calleddefault_thumb_file. For example:

sphinx_gallery_conf={...'default_thumb_file':'path/to/thumb/file.png',}

Adding line numbers to examples#

Line numbers can be displayed in listings by adding the globalline_numberssetting:

sphinx_gallery_conf={...'line_numbers':True,}

or by adding a comment to the example script, which overrides any globalsetting:

# sphinx_gallery_line_numbers = True

Removing config comments#

Some configurations can be specified within a file by adding a specialcomment with the pattern#sphinx_gallery_config[=value] to theexample source files. By default, the source files are parsed as is and thusthe comment will appear in the example.

To remove the comment from the rendered example set the option:

sphinx_gallery_conf={...'remove_config_comments':True,}

This only removes configuration comments from code blocks, not from textblocks. However, note that technically, file-level configuration comments willwork when put in either code blocks or text blocks.

Add your own first and last notebook cell#

Sphinx-Gallery allows you to add your own first and/or last cell toeverygenerated notebook. Adding a first cell can be useful for including code thatis required to run properly in the notebook, but not in a.py file. Bydefault, no first cell is added.

Adding a last cell can be useful for performing a desired action such asreporting on the user’s environment. By default no last cell is added.

You can choose whatever text you like by modifying thefirst_notebook_cellandlast_notebook_cell configuration parameters. For example, you can addthe following first cell:

# This cell is added by Sphinx-Gallery# It can be customized to whatever you like

Which is achieved by the following configuration:

sphinx_gallery_conf={...'first_notebook_cell':("# This cell is added by Sphinx-Gallery\n""# It can be customized to whatever you like\n")}

A last cell may be added similarly by setting thelast_notebook_cellparameter:

sphinx_gallery_conf={...'first_notebook_cell':("# This cell is added by Sphinx-Gallery\n""# It can be customized to whatever you like\n"),'last_notebook_cell':"# This is the last cell",}

If the value offirst_notebook_cell orlast_notebook_cell is set toNone, then no extra first or last cell will be added to the notebook.

Adding images to notebooks#

When notebooks are produced, by default (notebook_images=False) imagepaths from theimage directive in reST documentation blocks (not imagesgenerated from code) are included in markdown using their original paths. Thisincludes paths to images expected to be present on the local filesystem whichis unlikely to be the case for those downloading the notebook.

By settingnotebook_images=True, images will be embedded in the generatednotebooks via Base64-encodeddata URIs.As inclusion of images via data URIs can significantly increase size of thenotebook, it’s suggested this only be used when small images are used throughoutgalleries.

An alternative is to instead provide a prefix string that’ll be used for imagese.g. the root URL of where your documentation is hosted. So for example thefollowing configuration:

sphinx_gallery_conf={...'examples_dirs':['../examples'],'gallery_dirs':['auto_examples'],...'notebook_images':'https://project.example.com/en/latest/',...}

with an exampleimage directive in an reST documentation block being:

..image:: ../_static/example.jpg:alt: An example image

The image will be added to the generated notebook pointing to the source URLhttps://project.example.com/en/latest/_static/example.jpg. Note the imagepath in the reST examples above is a relative path, therefore the URL doesn’tcontainauto_examples as../ moved up a directory to the documentationsource directory. Both relative and absolute (from source directory) paths aresupported; so in the example above/_static/example.jpg would have resultedin the same URL being produced.

Note that the prefix is applied directly, so a trailing/ should beincluded in the prefix if it’s required.

Tip

If building multiple versions of your documentation on a hosted service andusing prefix, consider usingSphinx build -Dcommand line option to ensure links point to the correct version. Forexample:

sphinx-build\-bhtml\-Dsphinx_gallery_conf.notebook_images="https://project.example.com/docs/${VERSION}/"\source_dirbuild_dir

Using pypandoc to convert reST to markdown#

Sphinx-Gallery can usepypandoc(if installed) to convert reST text blocks to markdown for the iPythonnotebooks (.ipynb files) generated for each example. These are madeavailable for download, along with the raw.py version, at the bottomof each example.

The Sphinx-Gallery reST to markdown converter has limited support for morecomplex reST syntax. If your examples have more complex reST,pypandoc mayproduce better results. By default, the ‘pypandoc’ configuration is set toFalse andpypandoc is not used.

To usepypandoc you can set:

sphinx_gallery_conf={...'pypandoc':True,}

You can also use pandoc options by setting thepypandoc.convert_text()parametersextra_args andfilters. To use these parameters, set the‘pypandoc’ configuration to be a dictionary of keyword argument(s):

sphinx_gallery_conf={...'pypandoc':{'extra_args':['--mathjax',],'filters':['pandoc-citeproc',],}

Warning

Certain pandoc options may result in undesirable effects. Use with caution.

Using JUnit XML files#

Sphinx-Gallery can create a JUnit XML file of your example run times,successes, and failures. Setjunit configuration to the value of yourdesired JUnit file path, relative to the HTML output directory (which is bydefault/_build/html relative to yourconf.py file).For example, assuming output directory is the default, the configuration below createsa filejunit.xml indoc/_build/test-results/sphinx-gallery/:

sphinx_gallery_conf={...'junit':'../test-results/sphinx-gallery/junit.xml',}

By default, JUnit XML file generation is disabled (default value is:'junit':'').

Integration withCircleCI#

JUnit XML files are useful for example on CircleCI builds, where you can adda line like this to get a summary of your example run times in the CircleCI GUI(which will parse the file pathdoc/_build/test-results/sphinx-gallery/junit.xml and infer the testscame fromsphinx-gallery based on the nested subdirectory name):

-store_test_results:path:doc/_build/test-results-store_artifacts:path:doc/_build/test-results

For more information on CircleCI integration, peruse the relatedCircleCI docandblog post.

Parsing the XML file#

The JUnit XML file can also be parsed manually, e.g. to generate parametrizedtest cases withpytest to limit the maximum execution time. The followingcode block parses the XML file to create a list of test case dictionaries withthe execution time(s).

fromxml.etree.ElementTreeimportparsexml_path="doc/_build/html/sphinx-gallery/junit-results.xml"test_cases=[dict(case.attrib)forcaseinparse(xml_path).getroot().iterfind("testcase")]print(test_cases[0]["time"])0.10358190536499023

Setting log level#

Sphinx-Gallery logs output at several stages. Warnings can be generated forcode that requires case sensitivity (e.g.,plt.subplot andplt.Subplot)when building docs on a filesystem that does not support case sensitivenaming (e.g., Windows). In this case, by default alogger.warning isemitted, which will lead to a build failure when building with-W.The log level can be set with:

sphinx_gallery_conf={...'log_level':{'backreference_missing':'warning'},}

The only valid key currently isbackreference_missing.The valid values are'debug','info','warning', and'error'.

Disabling download button of all scripts#

By default Sphinx-Gallery collects all python scripts and all Jupyternotebooks from each gallery into zip files which are made available fordownload at the bottom of each gallery. To disable this behavior add to theconfiguration dictionary in yourconf.py file:

sphinx_gallery_conf={...'download_all_examples':False,}

Choosing the thumbnail image#

For examples that generate multiple figures, the default behavior will usethe first figure created in each as the thumbnail image displayed in thegallery. To change the thumbnail image to a figure generated later inan example script, add a comment to the example script to specify thenumber of the figure you would like to use as the thumbnail. For example,to use the 2nd figure created as the thumbnail:

# sphinx_gallery_thumbnail_number = 2

You can also use negative numbers, which counts from the last figure.For example -1 means using the last figure created in the exampleas the thumbnail:

# sphinx_gallery_thumbnail_number = -1

The default behavior issphinx_gallery_thumbnail_number=1. SeeChoosing the thumbnail figure for an exampleof this functionality.

Providing an image for the thumbnail image#

An arbitrary image can be used to serve as the thumbnail image for an example.To specify an image to serve as the thumbnail, add a comment to the examplescript specifying the path to the desired image. The path to the image shouldbe relative to theconf.py file and the comment should be somewherebelow the docstring (ideally in a code block, seeRemoving config comments).

For example, the following defines that the imagedemo.png in the folder_static/ should be used to create the thumbnail:

# sphinx_gallery_thumbnail_path = '_static/demo.png'

Note thatsphinx_gallery_thumbnail_number overrulessphinx_gallery_thumbnail_path. SeeProviding a figure for the thumbnail image for an example ofthis functionality.

Controlling thumbnail behaviour in failing examples#

By default, expected failing examples will have their thumbnail image as astamp with the word “BROKEN”. This behaviour is controlled bysphinx_gallery_failing_thumbnail, which is by defaultTrue. In caseswhere control over the thumbnail image is desired, this should be set toFalse. This will return thumbnail behaviour to ‘normal’, wherebythumbnail will be either the first figure created (or thedefault thumbnail if no figure is created)orprovided thumbnail:

# sphinx_gallery_failing_thumbnail = False

Compare the thumbnails ofExample that fails to execute (with normal thumbnail behaviour) (where theoption isFalse) andExample that fails to execute(where the option is the defaultTrue) for an example of thisfunctionality.

Generate Binder links for gallery notebooks (experimental)#

Sphinx-Gallery automatically generates Jupyter notebooks for anyexamples built with the gallery.Binder makes itpossible to create interactive GitHub repositories that connect to cloudresources.

If you host your documentation on a GitHub repository, it is possible toauto-generate a Binder link for each notebook. Clicking this link willtake users to a live version of the Jupyter notebook where they mayrun the code interactively. For more information see theBinder documentation.

Warning

Binder is still beta technology, so there may be instability in theexperience of users who click Binder links.

In order to enable Binder links with Sphinx-Gallery, you must specifya few pieces of information inconf.py. These are given as a nesteddictionary following the pattern below:

sphinx_gallery_conf={...'binder':{# Required keys'org':'<github_org>','repo':'<github_repo>','branch':'<github_branch>',# Can be any branch, tag, or commit hash. Use a branch that hosts your docs.'binderhub_url':'<binder_url>',# Any URL of a binderhub deployment. Must be full URL (e.g. https://mybinder.org).'dependencies':'<list_of_paths_to_dependency_files>',# Optional keys'filepath_prefix':'<prefix>'# A prefix to prepend to any filepaths in Binder links.'notebooks_dir':'<notebooks-directory-name>'# Jupyter notebooks for Binder will be copied to this directory (relative to built documentation root).'use_jupyter_lab':<bool># Whether Binder links should start Jupyter Lab instead of the Jupyter Notebook interface.}}

If a Sphinx-Gallery configuration for Binder is discovered, the following extrathings will happen:

  1. The dependency files specified independencies will be copied to abinder/ folder in your built documentation.

  2. The built Jupyter Notebooks from the documentation will be copied to afolder called<notebooks_dir/> at the root ofyour built documentation (they will follow the same folder hierarchy withinthe notebooks directory folder.

  3. The reST output of each Sphinx-Gallery example will now have alaunchbinder button in it.

  4. That button will point to a binder link with the following structure

    <binderhub_url>/v2/gh/<org>/<repo>/<ref>?filepath=<filepath_prefix>/<notebooks_dir>/path/to/notebook.ipynb

Below is a more complete explanation of each field.

org (type: string)

The GitHub organization where your documentation is stored.

repo (type: string)

The GitHub repository where your documentation is stored.

branch (type: string)

A reference to the version of your repository where your documentation exists.For example, if your built documentation is stored on agh-pages branch,then this field should be set togh-pages.

binderhub_url (type: string)

The full URL to a BinderHub deployment where you want your examples to run.One public BinderHub deployment is athttps://mybinder.org, though if you(and your users) have access to another, this can be configured with thisfield.

dependencies (type: list)

A list of paths (relative toconf.py) to dependency files that Binder usesto infer the environment needed to run your examples. For example, arequirements.txt file. These will be copied into a folder calledbinder/ in your built documentation folder. For a list of all the possibledependency files you can use, seethe Binder configuration documentation.

filepath_prefix (type: string | None, default:None)

A prefix to append to the filepath in the Binder links. You should use this ifyou will store your built documentation in a sub-folder of a repository,instead of in the root.

notebooks_dir (type: string, default:notebooks)

The name of a folder where the built Jupyter notebooks will be copied. Thisensures that all the notebooks are in one place (though they retain theirfolder hierarchy) in case you’d like users to browse multiple notebookexamples in one session.

use_jupyter_lab (type: bool, default:False)

Whether the default interface activated by the Binder link will be forJupyter Lab or the classic Jupyter Notebook interface.

Each generated Jupyter Notebook will be copied to the folderspecified innotebooks_dir. This will be a subfolder of the sphinx outputdirectory and included with your site build.Binder links will point to these notebooks.

Note

It is not currently possible to host notebooks generated bySphinx-Gallery with readthedocs.org, as RTD does not provide youwith a GitHub repository you could link Binder to. If you’d like touse readthedocs with Sphinx-Gallery and Binder links, you shouldindependently build your documentation and host it on a GitHub branchas well as building it with readthedocs.

See the Sphinx-GallerySphinx configuration filefor an example that uses thepublic Binder server.

Generate JupyterLite links for gallery notebooks (experimental)#

Sphinx-Gallery automatically generates Jupyter notebooks for any examples builtwith the gallery.JupyterLite makes itpossible to run an example in your browser. The functionality is quite similarto Binder in the sense that you will get a Jupyter environment where you canrun the example interactively as a notebook. The main differences from Binderare:

  • with JupyterLite, the example actually runs in your browser, there is no needfor a separate machine in the cloud to run your Python code. That means thatstarting a Jupyter server is generally quicker, no need to wait for theBinder image to be built

  • with JupyterLite, the first imports take time. At the time of writing(December 2024)importscipy can take ~15-30s. Some innocuously lookingPython code may just not work and break in an unexpected fashion. The Jupyterkernel is based on Pyodide, seehere for somePyodide limitations.

  • JupyterLite environments are not as flexible as Binder. For example, youcan not use a Docker image, but only the defaultPyodide environment. That means thatsome non pure-Python packages may not be available, see list ofavailablepackages in Pyodide.

Warning

JupyterLite is still beta technology and less mature than Binder, so theremay be instability or unexpected behaviour in the experience of users whoclick JupyterLite links.

In order to enable JupyterLite links with Sphinx-Gallery, you need to installthejupyterlite-sphinx package.Recent versions ofjupyterlite-sphinx and Sphinx-Gallery should be compatible,with each other, but we recommendjupyterlite-sphinx>=0.17.1.Forjupyterlite-sphinx>=0.8 you also need to installjupyterlite-pyodide-kernel. The latest released version is recommended, butrecent versions should work as well, this depends on the version of Pyodidethat you are using or planning to use.

You then need to addjupyterlite_sphinx to your Sphinx extensions inconf.py:

extensions=[...,'jupyterlite_sphinx',]

You can configure JupyterLite integration by settingsphinx_gallery_conf['jupyterlite'] inconf.py like this:

sphinx_gallery_conf={...'jupyterlite':{'use_jupyter_lab':<bool>,# Whether JupyterLite links should start Jupyter Lab instead of the Notebook interface.'notebook_modification_function':<str>,# fully qualified name of a function that implements JupyterLite-specific modifications of notebooks'jupyterlite_contents':<str>,# where to copy the example notebooks (relative to Sphinx source directory)}}

Below is a more complete explanation of each field.

use_jupyter_lab (type: bool, default:True)

Whether the default interface activated by the JupyterLite link will be forJupyter Lab or the RetroLab Notebook interface.

notebook_modification_function (type: str, default:None)

Fully qualified name of afunction that implements JupyterLite-specific modifications of notebooks. Bydefault, it isNone which means that notebooks are not going to bemodified. Its signature should benotebook_modification_function(json_dict:dict,notebook_filename:str)->None wherejson_dict is what you getwhen you dojson.load(open(notebook_filename)). The function is expectedto modifyjson_dict in place by adding notebook cells. It is not expectedto write to the file, sincesphinx-gallery is in charge of this.notebook_filename is provided for convenience because it is useful tomodify the notebook based on its filename. Potential usages of this functionare installing additional packages with a%pipinstallseaborn code cell,or adding a markdown cell to indicate that a notebook is not expected to workinside JupyterLite, for example because it is using packages that are notpackaged inside Pyodide. For backward compatibility it can also be a callablebut this will not be cached properly as part of the environment by Sphinx.

jupyterlite_contents (type: string, default:jupyterlite_contents)

The name of a folder where the built Jupyter notebooks will be copied,relative to the Sphinx source directory. This is used as Jupyterlitecontents.

You can set variables inconf.py to configurejupyterlite-sphinx, seethejupyterlite-sphinx documentation formore details.

If a Sphinx-Gallery configuration for JupyterLite is discovered, the followingextra things will happen:

  1. Configurejupyterlite-sphinx with some reasonable defaults, e.g. setjupyterlite_bind_ipynb_suffix=False.

  2. The built Jupyter Notebooks from the documentation will be copied to afolder called<jupyterlite_contents>/ (relative to Sphinx sourcedirectory)

  3. Ifnotebook_modification_function is notNone, this function isgoing to add JupyterLite-specific modifications to notebooks

  4. The reST output of each Sphinx-Gallery example will now have alaunchJupyterLite button in it.

  5. That button will point to a JupyterLite link which will start a Jupyterserver in your browser with the current example as notebook

If, for some reason, you want to enable thejupyterlite-sphinx extensionbut not use Sphinx-Gallery Jupyterlite integration you can do:

extensions=[...,jupyterlite_sphinx,]sphinx_gallery_conf={...'jupyterlite':None}

See the Sphinx-GallerySphinx configuration filefor an example that uses the JupyterLite integration.

Controlling notebook download links#

By default, links to download Jupyter noteooks and launch Binder or JupyterLite (ifenabled) are shown only for Python examples. If parsing other file extensions has beenenabled (using theexample_extensions option; seeParsing and executing examples via matching patterns), notebookdownloads can be enabled using thenotebook_extensions option. For example:

sphinx_gallery_conf={"notebook_extensions":{".py",".jl"}}

where the listed extensions are compared to file names in the gallery directory.

Note

Currently, all generated notebooks specify Python as the kernel. After downloading,the user will need to manually change to the correct kernel.

Making cell magic executable in notebooks#

Often times, tutorials will include bash code for the user to copy/paste intotheir terminal. This code should not be run when someone is building thedocumentation, as they will already have those dependencies in theirenvironment. Hence they are normally written as code blocks inside text:

#%%# Installing dependencies##     .. code-block:: bash##       pip install -q tensorflow#       apt-get -qq install curl

This works fine for the.py and.html files, but causes problems whenrendered as an Jupyter notebook. The downloaded.ipynb file will not havethose dependencies installed, and will not work without running the bash code.

To fix this, we can set thepromote_jupyter_magic flag inconf.py:

sphinx_gallery_conf={...'promote_jupyter_magic':True,}

If this flag isTrue, then when a Jupyter notebook is being built, any codeblock starting withJupyter cell magics (e.g.%%bash or%%writefile)will be turned into a runnable code block.

For our earlier example, we could change the Markdown text to:

#%%# Installing dependencies##     .. code-block:: bash##       %%bash#       pip install -q tensorflow#       apt-get -qq install curl

meaning TensorFlow and Curl would be automatically installed upon running theJupyter notebook. This works for any cell magic (not just those mentioned above)and only affects the creation of Jupyter notebooks.

Warning

It is good practice to ensure the.py and.html files match the.ipynbfiles as closely as possible. This functionality should only be used when therelevant code is intended to be executed by the end user.

Building without executing examples#

Sphinx-Gallery can parse all your examples and build the gallerywithout executing any of the scripts. This is just for speedvisualization processes of the gallery and the size it takes yourwebsite to display, or any use you can imagine for it.

This can be done by setting theplot_gallery configuration in thesphinx_gallery_conf dictionary inside yourconf.py:

sphinx_gallery_conf={...'plot_gallery':'False',}

You can also change this via theSphinx build option -D,which can be used to add a ‘no-plot’ target to yourMakefile:

html-noplot:$(SPHINXBUILD)-Dplot_gallery=0-bhtml$(ALLSPHINXOPTS)$(SOURCEDIR)$(BUILDDIR)/html@echo@echo"Build finished. The HTML pages are in$(BUILDDIR)/html."

Remember that forMakefile white space is significant and the indentation are tabsand not spaces.

The highest precedence is always given to the-D flag of thesphinx-build command, which effectively makes the value set in yourconf.pyfile the ‘default’.

Note

If addinghtml-noplot to yourMakefile, you will also need toexplicitly set the default value forplot_gallery in thesphinx_gallery_conf dictionary inside yourconf.py file to avoida sphinx configuration warning.

Compressing images#

When writing PNG files (the default scraper format), Sphinx-Gallery can beconfigured to useoptipng to optimize the PNG file sizes. Typically thisyields roughly a 50% reduction in file sizes, thus reducing the loading timeof galleries. However, it can increase buildtime. The allowed values are'images' and'thumbnails', or atuple/list (to optimize both), such as:

sphinx_gallery_conf={...'compress_images':('images','thumbnails'),}

The default is() (no optimization) and a warning will be emitted ifoptimization is requested butoptipng is not available. You can also passadditional command-line options (starting with'-'), for example tooptimize less but speed up the build time you could do:

sphinx_gallery_conf={...'compress_images':('images','thumbnails','-o1'),}

See$optipng--help for a complete list of options.

Multi-resolution images#

Web browsers allow asrcset parameter to the<img> tag thatallows the browser to supportresponsive resolution imagesfor hi-dpi/retina displays. Sphinx Gallery supports this via theimage_srcset parameter:

sphinx_gallery_conf={...'image_srcset':["2x"],}

that saves a 1x image at the normal figure dpi (usually 100 dpi) and a 2xversion at twice the density (e.g. 200 dpi). The default is no extra images('image_srcset':[]), and you can specify other resolutions if desired as alist:["2x","1.5x"].

The matplotlib scraper creates a custom image directive,image-sg in therst file:

..image-sg::/examples/images/sphx_glr_test_001.png:alt:test:srcset:/examples/images/sphx_glr_test_001.png,/examples/images/sphx_glr_test_001_2_0x.png2.0x:class:sphx-glr-single-img

This is converted to html by the custom directive as:

..<imgsrc="../_images/sphx_glr_test_001.png"alt="test",class="sphx-glr-single-img",srcset="../_images/sphx_glr_test_001.png, ../_images/sphx_glr_test_001_2_0x.png 2.0x>

This leads to a larger website, but clients that support thesrcset tag will onlydownload the appropriate-sized images.

Note that the..image-sg directive currently ignores other..imagedirective tags likewidth,height, andalign. It also only workswith thehtml andlatex builders.

Image scrapers#

Image scrapers are plugins that allow Sphinx-Gallery to detect images producedduring execution of your examples, and then embed them into documentation.Scrapers can be activated by appending scraper names to the'image_scrapers' tuple in your Sphinx-Gallery configuration. For example,to scrape matplotlib images you can do:

sphinx_gallery_conf={...'image_scrapers':('matplotlib',),}

The default value is'image_scrapers':('matplotlib',) which only scrapesMatplotlib images. Note that this includes any images produced by packages thatare based on Matplotlib, for example Seaborn or Yellowbrick.

Matplotlib animations#

If you wish to embedmatplotlib.animation.Animations as animations ratherthan a single static image of the animation figure, you should use thematplotlib_animations configuration. It accepts either a bool, indicating whetheranimations should be enabled, or a tuple of the format: (enabled: bool, format: str):

sphinx_gallery_conf={...'matplotlib_animations':(True,'mp4'),}

matplotlib_animations isFalse by default.

Any file format supported by Matplotlib for animations is allowed. If no formatis specified (i.e., it is a single bool), or it isNone, then the format isdetermined byrcParams['animation.html'] and related options in yourmatplotlib rcParams.This means that it can be set inside your code block, though note that Sphinx-Gallerywill reset Matplotib defaults before each example file executes (seeResetting modules).

If the format is'html5' or'jshtml', the animation will effectivelybe embedded in the resulting HTML file. Otherwise the animation will be savedin an external file, thus reducing the size of the ReST file generated.If you request a format that saves to an external file, you will need thesphinxcontrib-video extensioninstalled in your environment.

Note that whilematplotlib_animations allows you to set thercParams['animation.html'] globally, setting it inside a code block willoverride the global setting.

It’s also recommended to ensure that “FFmpeg” or “imagemagick” is available as awriter. Usematplotlib.animation.ImageMagickWriter.isAvailable()ormatplotlib.animation.FFMpegWriter.isAvailable()to check.We recommend FFMpeg writer, unless you are using Matplotlib <3.3.1.

Supported scrapers#

The following scrapers are supported:

  • matplotlib

    Sphinx-Gallery maintains a scraper formatplotlib figures via the string'matplotlib'.

  • PyVista

    PyVista maintains a scraper(for PyVista >= 0.20.3) enabled by the string'pyvista'.

  • PyGMT

    Seetheir website for more information onhow to integrate with Sphinx-Gallery.

  • qtgallery

    This library provides a scraper for Qt windows. Seetheir repositoryfor instructions on integrating with Sphinx-Gallery.

  • plotly

    This library provides a scraper, though it is also possible to capture plotlyfigures usingcapture_repr configuration.SeeExample with the plotly graphing library for details.

It is possible to write custom scrapers for images generated by packagesoutside of those listed above. This is accomplishedby writing your own Python function to define how to detect and retrieveimages produced by an arbitrary package. For instructions, seeWrite a custom image scraper. If you come up with an implementation that would beuseful for general use (e.g., a custom scraper for a plotting library)feel free to add it to the list above (see discussionhere)!

Using multiple code blocks to create a single figure#

By default, images are scraped following each code block in an example. Thus,the following produces two plots, with one plot per code block:

# %%# This first code block produces a plot with two linesimportmatplotlib.pyplotaspltplt.plot([1,0])plt.plot([0,1])# %%# This second code block produces a plot with one lineplt.plot([2,2])plt.show()

However, sometimes it can be useful to use multiple code blocks to create asingle figure, particularly if the figure takes a large number commands thatwould benefit from being interleaved with text blocks. The optional flagsphinx_gallery_defer_figures can be inserted as a comment anywhere in a codeblock to defer the scraping of images to the next code block (where it can befurther deferred, if desired). The following produces only one plot:

# %%# This first code block does not produce any plotimportmatplotlib.pyplotaspltplt.plot([1,0])plt.plot([0,1])# sphinx_gallery_defer_figures# %%# This second code block produces a plot with three linesplt.plot([2,2])plt.show()

Controlling the layout of multiple figures from the same code block#

By default, multiple figures generated from the same code block are stackedside-by-side. Particularly for wide figures, this can lead to cases where images arehighly shrunk, losing their legibility. This behaviour can be controlled using twooptional variables:

  • a file-widesphinx_gallery_multi_image variable

  • a code block-specificsphinx_gallery_multi_image_block variable

The default behaviour is to treat these variables as being set to"multi", whichcauses figures to be stacked side-by-side. Setting these variables to"single" willallow figures produced from a code block to be displayed as a single column.

For instance, adding:

# sphinx_gallery_multi_image = "single"

somewhere in an example file will cause images from all code blocks where multiplefigures are produced to be displayed in a single column.

Alternatively, adding:

# sphinx_gallery_multi_image_block = "single"

to a code block will cause multiple figures from only that code block to be displayed ina single column.

Conversely, ifsphinx_gallery_multi_image="single" is set for the whole file,addingsphinx_gallery_multi_image_block="multi" can restore the default behaviourfor a single code block.

See the exampleForce plots to be displayed on separate lines for ademonstration of this functionality.

Hiding lines of code#

Normally, Sphinx-Gallery will render every line of Python code when buildingHTML and iPython notebooks. This is usually desirable, as we want to ensure thePython source files, HTML, and iPython notebooks all do the same thing.

However, it is sometimes useful to have Python code that runs, but is notincluded in any user-facing documentation. For example, suppose we wanted toadd someassert statements to verify the docs were built successfully, butdid not want these shown to users. We could use thesphinx_gallery_start_ignoreandsphinx_gallery_end_ignore flags to achieve this:

model.compile()# sphinx_gallery_start_ignoreassertlen(model.layers)==5assertmodel.count_params()==219058# sphinx_gallery_end_ignoremodel.fit()

When the HTML or iPython notebooks are built, this code block will be shown as:

model.compile()model.fit()

Thesphinx_gallery_start_ignore andsphinx_gallery_end_ignore flags maybe used in any code block, and multiple pairs of flags may be used in the sameblock. Every start flag must always have a corresponding end flag, or an errorwill be raised during doc generation. These flags and the code between them arealways removed, regardless of whatremove_config_comments is set to.

Note that any output from the ignored code will still be captured.

Warning

This flag should be used sparingly, as it makes the.py source files lessequivalent to the generated.html and.ipynb files. It is bad practiceto use this when other methods that preserve this relationship are possible.

Generating dummy images#

For quick visualization of your gallery, especially during the writing process,Sphinx-Gallery allows you to build your gallery without executing thecode (seeBuilding without executing examples andfilename/ignore patterns). This however,can cause warnings about missing image files if you have manually writtenlinks to automatically generated images. To prevent these warnings you cantell Sphinx-Gallery to create a number of dummy images for an example.

For example, you may have an example (‘my_example.py’) that generates 2 figures,which you then reference manually elsewhere, e.g.,:

Below is a great figure:..figure:: ../auto_examples/images/sphx_glr_my_example_001.pngHere is another one:..figure:: ../auto_examples/images/sphx_glr_my_example_002.png

To prevent missing image file warnings when building without executing, youcan add the following to the example file:

# sphinx_gallery_dummy_images=2

This will cause Sphinx-Gallery to generate 2 dummy images with the samenaming convention and stored in the same location as images that would begenerated when building with execution. No dummy images will be generatedif there are existing images (e.g., from a previous run of the build),so they will not be overwritten.

Note

This configurationonly works when the example is set to not execute(i.e., theplot_gallery is'False', the example is inignore_pattern or the example is not infilename_pattern - seefilename/ignore patterns). This means that you willnot need to remove anysphinx_gallery_dummy_images lines in yourexamples when you switch to building your gallery with execution.

Resetting modules#

Often you wish to “reset” the behavior of your visualization packages in orderto ensure that any changes made to plotting behavior in one example do notpropagate to the other examples.

By default, before each example file executes, Sphinx-Gallery willresetmatplotlib (by usingmatplotlib.pyplot.rcdefaults() andreloading submodules that populate the units registry) andseaborn(by trying to unload the module fromsys.modules). This is equivalent to thefollowing configuration:

sphinx_gallery_conf={...'reset_modules':('matplotlib','seaborn'),}

Currently, Sphinx-Gallery natively supports resettingmatplotlib andseaborn. However, you can also add your own custom function tothis tuple in order to define resetting behavior for other visualization libraries.

To do so, follow the instructions inResetting before each example.

Order of resetting modules#

By default, Sphinx-Gallery will reset modules before each example is run.The choices forreset_modules_order arebefore (default),after, andboth. If the last example run in Sphinx-Gallery modifies a module, it isrecommended to useafter orboth to avoid leaking out a modified module toother parts of the Sphinx build process. For example, setreset_modules_ordertoboth in the configuration:

sphinx_gallery_conf={...'reset_modules_order':'both',}

Custom functions can be constructed to have custom functionality depending onwhether they are called before or after the examples. SeeResetting before each examplefor more information.

Dealing with failing Gallery example scripts#

As your project evolves some of your example scripts might stopexecuting properly. Sphinx-Gallery will assist you in the discovery processof those bugged examples. The default behavior is to replace thethumbnail of those examples in the gallery with the brokenthumbnail. That allows you to find with a quick glance of the gallerywhich examples failed. Broken examples remain accessible in the htmlview of the gallery and the traceback message is written for thefailing code block. Refer to exampleExample that fails to execute to view the defaultbehavior.

The build is also failed exiting with code 1 and giving you a summaryof the failed examples with their respective traceback. This way youare aware of failing examples right after the build and can find themeasily.

There are some additional options at your hand to deal with broken examples.

Abort build on first fail#

Sphinx-Gallery provides the early fail option. Inthis mode the gallery build process breaks as soon as an exceptionoccurs in the execution of the examples scripts. This can by activated via theabort_on_example_error configuration, which can be setsphinx_gallery_confdictionary inside yourconf.py configuration file:

sphinx_gallery_conf={...'abort_on_example_error':True,}

You can also change this via theSphinx build option -D,which can be used to add a ‘abort_on_example_error’ target to yourMakefile:

html_abort_on_example_error:$(SPHINXBUILD)-Dabort_on_example_error=1-bhtml$(ALLSPHINXOPTS)$(BUILDDIR)/html@echo@echo"Build finished. The HTML pages are in$(BUILDDIR)/html."

Remember that forMakefile white space is significant and the indentationare tabs and not spaces.

The highest precedence is always given to the-D flag of thesphinx-build command, which effectively makes the value set in yourconf.pyfile the ‘default’.

Don’t fail the build if specific examples error#

It might be the case that you want to keep the gallery even withfailed examples. Thus you can configure Sphinx-Gallery to allowcertain examples to fail and still exit with a 0 exit code. For thisyou need to list all the examples you want to allow to fail duringbuild. Change yourconf.py accordingly:

sphinx_gallery_conf={...'expected_failing_examples':['../examples/plot_raise.py']}

Here you list the examples you allow to fail during the build process,keep in mind to specify the full relative path from yourconf.py tothe example script.

Note

If an example is expected to fail, Sphinx-Gallery will error ifthe example runs without error.

Never fail the build on error#

Sphinx-Gallery can be configured to only log warnings when examples fail.This means that sphinx will only exit with a non-zero exit code if the-Wflag is passed tosphinx-build. This can be enabled by setting:

sphinx_gallery_conf={...'only_warn_on_example_error':True}

Build examples in parallel#

Sphinx-Gallery can be configured to run examples simultaneously usingjoblib. This can be enabled by setting:

sphinx_gallery_conf={...'parallel':2,}

If anint, then that number of jobs will be passed tojoblib.Parallel.IfTrue, then the same number of jobs will be used as the-j flag forSphinx.

Warnings emitted byjoblib during documentation building (e.g., theUserWarning about aworker restarting) are emittedduring gallery generation at the same time as warnings from examplecode execution. These can be filtered out withwarnings.filterwarnings (seeRemoving warnings). This is particularlyimportant to do if you have tweaked warning handling in your documentation buildto treat warnings as errors, e.g., with a line likewarnings.filterwarnings("error) which converts all warnings into errors. Inthis case, if joblib emits a warning during build of an example, this example will failunexpectedly unless they are filtered out. Note that this differs from the warningsaffected by the-W /--fail-on-warningsphinx-build flag, which convertsSphinx warnings during documentation building into errors.

Warning

Some packages might not play nicely with parallel processing, so this featureis consideredexperimental!

For example, you might need to set variables or call functions in acustom resetter to ensure that all spawned processes areproperly set up and torn down. Parallelism is achieved through the Loky backend ofjoblib, seeEmbarrassingly parallel for loops for documentation of many relevant conisderations(e.g., pickling, oversubscription of CPU resources, etc.).

Using parallel building will also disable memory measurements.

Enabling the example recommender system#

Sphinx-Gallery can be configured to generate content-based recommendations foran example gallery. A list of related examples is automatically generated bycomputing the closest examples in theTF-IDF space of their text contents.Only examples within a single gallery (including it’s sub-galleries) are used tocompute the closest examples. The most similar content is then displayed at the bottomof each example as a set of thumbnails.

The recommender system can be enabled by settingenable toTrue. Toconfigure it, pass a dictionary to thesphinx_gallery_conf, e.g.:

sphinx_gallery_conf={..."recommender":{"enable":True,"n_examples":5,"min_df":3,"max_df":0.9},}

The only necessary parameter isenable. If any other parameters is notspecified, the default value is used. Below is a more complete explanation ofeach field:

enable (type: bool, default: False)

Whether to generate recommendations inside the example gallery. Enabling thisfeature requires addingnumpy to the dependencies.

n_examples (type: int, default: 5)

Number of most relevant examples to display.

min_df (type: float in range [0.0, 1.0] | int, default: 3)

When building the vocabulary ignore terms that have a document frequencystrictly lower than the given threshold. If float, the parameter represents aproportion of documents, integer represents absolute counts. This value isalso called cut-off in the literature.

max_df (type: float in range [0.0, 1.0] | int, default: 0.9)

When building the vocabulary ignore terms that have a document frequencystrictly higher than the given threshold. If float, the parameter represents aproportion of documents, integer represents absolute counts.

rubric_header (type: str, default: “Related examples”)

Customizable rubric header. It can be edited to more descriptive text or toadd external links, e.g. to the API doc of the recommender system on theSphinx-Gallery documentation.

The parametersmin_df andmax_df can be customized by the user to trimthe very rare/very common words. This may improve the recommendations quality,but more importantly, it spares some computation resources that would be wastedon non-informative tokens.

Currently example recommendations are only computed for.py files.

Setting gallery thumbnail size#

By default Sphinx-Gallery will generate thumbnails at size(400,280).The thumbnail image will then be scaled to the size specified bythumbnail_size, adding pillarboxes or letterboxes as necessary tomaintain the original aspect ratio. The defaultthumbnail_size is(400,280) (no scaling) and can be changed via thethumbnail_sizeconfiguration, e.g.:

sphinx_gallery_conf={...'thumbnail_size':(250,250),}

The gallery uses various CSS classes to display these thumbnails, whichdefault to maximum 160x112px. To change this you can modify the default CSS byincluding your own CSS file via the Sphinx configurationhtml_static_path (which will override default CSS classesinSphinx-Gallery CSS files).The following CSS would display the images at 250x250px instead of the default160x112px:

.sphx-glr-thumbcontainer{min-height:320px!important;margin:20px!important;}.sphx-glr-thumbcontainer.figure{width:250px!important;}.sphx-glr-thumbcontainerimg{max-height:250px!important;width:250px!important;}.sphx-glr-thumbcontainera.internal{padding:270px10px0!important;}

Note

The default value ofthumbnail_size will change from(400,280) (2.5x maximum specified by CSS) to(320,224)(2x maximum specified by CSS) in version 0.9.0. This is toprevent unnecessary over-sampling.

Minimal reported time#

By default, Sphinx-Gallery logs and embeds in the html output the time it tookto run each script. If the majority of your examples runs quickly, you may notneed this information.

Themin_reported_time parameter can be set to a number of seconds. Theduration of scripts that ran faster than that amount will not be logged norembedded in the html output.

Write computation times#

Set toFalse if you want to omit computation times from all gallery outputs.This helps with reproducible builds.Default isTrue unless theSOURCE_DATE_EPOCH environment variable is set.

If you are interested in using execution time and execution success and failure data,seeUsing JUnit XML files.

Showing memory consumption#

Sphinx-Gallery can usememory_profiler, if installed, to report the peakmemory during the run of an example. After installingmemory_profiler,you can do:

sphinx_gallery_conf={...'show_memory':True,}

It’s also possible to use your own custom memory reporter, for exampleif you would rather see the GPU memory. In that case,show_memory mustbe a callable that takes a single function to call (i.e., one generatedinternally to run an individual script code block), and returns a two-elementtuple containing:

  1. The memory used in MiB while running the function, and

  2. The function output

A version of this that would always report 0 memory used would be:

sphinx_gallery_conf={...'show_memory':lambdafunc:(0.,func()),}

Show signature#

By default, Sphinx-Gallery writes aGenerated by … notice in thegenerated output.

Theshow_signature parameter can be used to disable it.

Controlling what output is captured#

Note

Configurecapture_repr to be an empty tuple (i.e.,capture_repr: ())to return to the output capturing behaviour prior to release v0.5.0.

Thecapture_repr configuration allows the user to control what outputis captured, while executing the example.py files, and subsequentlyincorporated into the built documentation. Data directed to standard outputis always captured. The value of the last statement ofeach code block,ifit is an expression, can also be captured. This can be done by providingthe name of the ‘representation’ method to be captured in thecapture_reprtuple, in order of preference. The representation methods currently supportedare:

  • __repr__ - returns the official string representation of an object. Thisis what is returned when your Python shell evaluates an expression.

  • __str__ - returns a string containing a nicely printable representationof an object. This is what is used when youprint() an object or pass ittoformat().

  • _repr_html_ - returns a HTML version of the object. This method is onlypresent in some objects, for example, pandas dataframes.

Output capture can be controlled globally by thecapture_repr configurationsetting, file-by-file by adding a comment to the example file, which overridesany global setting:

# sphinx_gallery_capture_repr = ()

, or block-by-block by adding a comment to the code block, which overrides anyglobal or file setting:

# sphinx_gallery_capture_repr_block = ()

The default setting is:

sphinx_gallery_conf={...'capture_repr':('_repr_html_','__repr__'),}

With the default setting Sphinx-Gallery would first attempt to capture the_repr_html_ of the last statement of a code block,if it is anexpression. If this method does not exist for the expression, the second‘representation’ method in the tuple,__repr__, would be captured. If the__repr__ also does not exist (unlikely for non-user defined objects),nothing would be captured. Data directed to standard output isalwayscaptured. For several examples, seeCapturing output representations.

To capture only data directed to standard output, configure'capture_repr'to be an empty tuple:'capture_repr':(). This will imitate the behaviourof Sphinx-Gallery prior to v0.5.0.

From another perspective, take for example the following code block:

print('Hello world')a=2a# this is an expression

'Helloworld' would be captured for everycapture_repr setting as thisis directed to standard output. Further,

  • ifcapture_repr is an empty tuple, nothing else would be captured.

  • ifcapture_repr is('__repr__'),2 would also be captured.

  • ifcapture_repr is('_repr_html_','__repr__') (the default)Sphinx-Gallery would first attempt to capture_repr_html_. Since thisdoes not exist fora, it will then attempt to capture__repr__.The__repr__ method does exist fora, thus2 would be alsocaptured in this case.

Matplotlib note: if the'capture_repr' tuple includes'__repr__'and/or'__str__', code blocks which have a Matplotlib function call as thelast expression will generally produce a yellow output box in the builtdocumentation, as well as the figure. This is because matplotlib function callsusually return something as well as creating/amending the plot in standardoutput. For example,matplotlib.plot() returns a list ofLine2D objectsrepresenting the plotted data. This list has a__repr__ and a__str__method which would thus be captured. You can prevent this by:

  • assigning the (last) plotting function to a temporary variable. For example:

    importmatplotlib.pyplotasplt_=plt.plot([1,2,3,4],[1,4,9,16])
  • addplt.show() (which does not return anything) to the end of yourcode block. For example:

    importmatplotlib.pyplotaspltplt.plot([1,2,3,4],[1,4,9,16])plt.show()
  • add a#sphinx_gallery_capture_repr_block=() comment to the code block.The unwanted string output will not occur if'capture_repr' is an emptytuple or, at least, does not contain__repr__ or__str__.For example:

    # sphinx_gallery_capture_repr_block = ()importmatplotlib.pyplotaspltplt.plot([1,2,3,4],[1,4,9,16])

Note for Plotly users

The suggestions above also apply to Plotly users. Plotly figures haveseveralupdate methods thatimplicitly return the updated figure object. You can set a block-level#sphinx_gallery_capture_repr_block=() comment to prevent thesefrom being captured, or assign the return values to a variable (e.g.,fig=fig.update_layout(...)).

Prevent capture of certain classes#

If you wish to capture a representation of the last expression of each codeblocksunless the last expression is of a certain type, you can use'ignore_repr_types'.'ignore_repr_types' is by default an empty rawstring (r''), meaning no types are ignored. To exclude specific type(s)from being captured,'ignore_repr_types' can be set to a regularexpression matching the name(s) of the type(s) to be excluded.

For example, the configuration below would capture the__repr__ of thelast expression of each code block unless the name of thetype() of the lastexpression includes the string ‘matplotlib.text’or ‘matplotlib.axes’.This would prevent capturing of all subclasses of ‘matplotlib.text’, e.g.expressions of type ‘matplotlib.text.Annotation’, ‘matplotlib.text.OffsetFrom’etc. Similarly subclasses of ‘matplotlib.axes’ (e.g. ‘matplotlib.axes.Axes’,‘matplotlib.axes.Axes.plot’ etc.) will also not be captured.

sphinx_gallery_conf={...'capture_repr':('__repr__'),'ignore_repr_types':r'matplotlib\.(text|axes)',}

Nesting gallery sections#

nested_sections lets you control how galleryindex.rst files are generatedwhen yourgallery has subsections(sub-folders insideexamples_dirs, akasub-galleries). This can be useful forcontrolling sidebar appearance. The default is set tonested_sections=Truebecause it generally works with the popularpydata-sphinx-themetheme. It can however, cause undesirable duplication in the sidebar with otherthemes so users are advised to choose the most suitablenested_sections settingfor their theme.

With defaultnested_sections=True, Sphinx-Gallery will use theGALLERY_HEADER.[ext] (orREADME.[ext] for backward-compatibility) filesfor the parent gallery and each subsection to build separate index files for theparent gallery and each subsection.subsection index files will contain the subsection’s header (from theGALLERY_HEADER.[ext] file) and a toctreelinking to each gallery example in the subsection.The parent gallery’s mainindex.rst file will contain, in sequence:

  • parent gallery header followed by gallery thumbnails,

  • a toctree linking to each gallery example in the parent gallery,

  • subsection header followed by subsection thumbnails, for all subsections,

  • a second toctree, at the end of the file, linking to all subsection index files.

The generated file structure and toctrees mimic that of the parent gallery folder,which may be needed for generating sidebars with nested sections for some themes.

For other themes, having two toctrees can cause undesirable duplication in the sidebar.In this case you can try moving all parent gallery examples to their own sub-folder,as this will result in a single toctree in the parent galleryindex.rst, orusingnested_sections=False.

nested_sections=False makes Sphinx-Gallery behave as it used toprior to version 0.10.2.Specifically, it will generate a single index file for the whole gallery.This index file will contain headers for the parent gallery and each subsection, witheach header followed by a toctree that links to every example in theparent gallery/subsection.For some themes, sidebars generated using these toctrees would list all gallery itemswith a flat structure and not reflect the nested folder structure of sub-galleries.

Manually passing files#

By default, Sphinx-Gallery creates all the files that are written in thesphinx-build directory, either by generating reST and images from a*.pyin the gallery-source, or from creatingindex.rst fromGALLERY_HEADER.rst (orREADME.[rst/txt] for backward-compatibility)in the gallery-source. However, sometimes it is desirable to pass filesfrom the gallery-source to the sphinx-build. For example, you may wantto pass an image that a gallery refers to, but does not generate itself.You may also want to pass raw reST from the gallery-source to thesphinx-build, because that material fits in thematically with your gallery,but is easier to write as reST. To accommodate this, you may setcopyfile_regex insphinx_gallery_conf. The following copiesacross reST files.

sphinx_gallery_conf={...'copyfile_regex':r'.*\.rst',}

Note that if you copy across reST files, for instance, it is yourresponsibility to ensure that they are in a sphinxtoctree somewherein your document. You can, of course, add atoctree to yourGALLERY_HEADER.rst.

Manually passingindex.rst#

You can bypass Sphinx-Gallery automatically creating anindex.rst from aGALLERY_HEADER.rst in a gallery directory or nested sub-gallery directory. If yourcopyfile_regex includesindex.rst, and you have anindex.rst in thegallery-source (i.e., aexamples_dirs directory),Sphinx-Gallery will use that instead and not make an index file for that galleryor any of its sub-galleries.If you pass your ownindex.rst file, you are responsible foradding your own Sphinxtoctree in that index (or elsewhere in your Sphinxdocumentation) that includes any gallery items or other files in thatdirectory. You are also responsible for adding any necessaryindex.rstfiles for that gallery’s sub-galleries.

The following is an example ofindex.rst that handles a gallery withsub-galleries and can insert an example from one sub-gallery into another onewhile preserving the nested structure in the TOC tree.:

Examples gallery================Subgallery 1------------..toctree:::maxdepth: 2:glob::hidden:    subgallery1/plot_*..minigallery:: ../../examples/subgallery1/plot_*.pySubgallery 2------------..toctree:::maxdepth: 2:glob::hidden:    subgallery2/plot_*..minigallery::    ../../examples/subgallery2/plot_*.py    ../../examples/subgallery1/plot_example_in_both.py

Showing API Usage#

Graphs and documentation of both unused API entries and the examples thateach API entry is used in are generated in the sphinx output directory undersg_api_usage.html. See theSphinx-Gallery API usage documentation and graphsfor example. In large projects, there are many modules and, since a graphof API usage is generated for each module, this can use a lot of resourcessoshow_api_usage is set to'unused' by default. The unused APIentries are all shown in one graph so this scales much better for largeprojects. Settingshow_api_usage toTrue will make one graph permodule showing all of the API entries connected to the example that theyare used in. This could be helpful for making a map of which examples tolook at if you want to learn about a particular module. Settingshow_api_usage toFalse will not make any graphs or documentationabout API usage. Note,graphviz is required for making the unused andused API entry graphs.

Ignoring API entries#

By default,api_usage_ignore='.*__.*__' ignores files that match thisregular expression in documenting and graphing the usage of API entrieswithin the example gallery. This regular expression can be modified toignore any kind of file that should not be considered. The default regularexpression ignores functions like__len__() for which it may not bedesirable to document if they are used in examples.

On this page