# Configuration¶

Configuration and customization of sphinx-gallery is done primarily with a dictionary specified in your conf.py file. A list of the possible keys are listed below and explained in greater detail in subsequent sections.

## List of config options¶

Most sphinx-gallery configuration options are set in the Sphinx conf.py file:

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

See also Removing config comments to hide these comments from the rendered examples.

Some options can be set during the build execution step, e.g. using a Makefile:

And some things can be tweaked directly in CSS:

## Manage multiple galleries¶

Sphinx-Gallery only supports up to sub-folder level in its gallery directories. This might be a limitation for you. Or you might want to have separate galleries for different purposes, an examples gallery and a tutorials gallery. For this you use in your Sphinx conf.py file a list of directories in the sphinx configuration dictionary:

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


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

Note

If your examples take a long time to run, consider looking at the execution times file that is generated for each gallery dir (as long as any examples were actually executed in that directory during the build).

## Parsing and executing examples via matching patterns¶

By default, Sphinx-Gallery will parse and add all files with a .py extension to the gallery, but only execute files beginning with plot_. These behaviors are controlled by the ignore_pattern and filename_pattern entries, which have the default values:

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


To omit some files from the gallery entirely (i.e., not execute, parse, or add them), you can change the ignore_pattern option. To choose which of the parsed and added Python scripts are actualy executed, you can modify filename_pattern. For example:

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


will build all examples starting with plot_compute_. The key filename_pattern (and ignore_pattern) accepts regular expressions which will be matched with the full path of the example. This is the reason the leading '/' is required. Users are advised to use re.escape(os.sep) instead of '/' if they want to be agnostic to the operating system.

The filename_pattern option is also useful if you want to build only a subset of the examples. For example, you may want 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 dot r'\.' as otherwise python regular expressions matches any character. Nevertheless, as one is targeting a specific file, it would match the dot in the filename even without this escape character.

Note

Sphinx-gallery only re-runs examples that have changed (according to their md5 hash). You can delete the associated MD5 files (e.g., ./auto_examples/plot_awesome_example.py.md5) to force a rebuild if you have not changed the example itself between subsequent sphinx calls.

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 skip building examples starting with plot_long_examples_, you would do:

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


As the patterns are parsed as regular expressions, users are advised to consult the regular expressions module for more details.

Note

Remember that Sphinx allows overriding conf.py values from the command line, so you can for example build a single example directly via something like:

$sphinx-build -D sphinx_gallery_conf.filename_pattern=plot_specific_example\.py ...  ## Add mini-galleries for API documentation¶ When documenting a given function/class, Sphinx-Gallery enables you to link to any examples that either: 1. Use the function/instantiate the class in the code. 2. Refer to that function/class using sphinx markup :func:/:class: in a documentation block. The former is useful for auto-documenting functions that are used and classes that are explicitly instantiated. The latter is useful for classes that are typically implicitly returned rather than explicitly instantiated (e.g., matplotlib.axes.Axes which is most often instantiated only indirectly within function calls). For example, we can embed a small gallery of all examples that use or refer to numpy.exp, which looks like this: ### Examples using numpy.exp¶ For such behavior to be available, you have to activate it in your Sphinx-Gallery configuration conf.py file with: sphinx_gallery_conf = { ... # directory where function granular galleries are stored 'backreferences_dir' : 'gen_modules/backreferences', # Modules for which function level galleries are created. In # this case sphinx_gallery and numpy in a tuple of strings. 'doc_module' : ('sphinx_gallery', 'numpy')}  The path you specify in backreferences_dir (here we choose gen_modules/backreferences) will be populated with ReStructuredText files. Each will contain a reduced version of the gallery specific to every function used across all the examples galleries and belonging to the modules listed in doc_module. Keep in mind that the path set in backreferences_dir is relative to the conf.py file. Then within your sphinx documentation .rst files you write these lines to include this reduced version of the Gallery, which has examples in use of a specific function, in this case numpy.exp: .. include:: gen_modules/backreferences/numpy.exp.examples .. raw:: html <div class="sphx-glr-clear"></div>  The include directive takes a path relative to the rst file it is called from. In the case of this documentation file (which is in the same directory as conf.py) we directly use the path declared in backreferences_dir followed by the function whose examples we want to show and the file has the .examples extension. ## Using a custom default thumbnail¶ In case you want to use your own image for the thumbnail of examples that do not generate any plot, you can specify it by editing your Sphinx conf.py file. You need to add to the configuration dictionary a key called default_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 global line_numbers setting: sphinx_gallery_conf = { ... 'line_numbers': True, }  or by adding a comment to the example script, which overrides any global setting: # sphinx_gallery_line_numbers = True  ## Removing config comments¶ Some configurations can be done on a file-by-file basis by adding a special comment with the pattern # sphinx_gallery_config = value to the example source files. By default, the source files are parsed as is and thus the comment will appear in the example. To remove the comment from the rendered example set the option: sphinx_gallery_conf = { ... 'remove_config_comments': True, }  ## Add your own first notebook cell¶ Sphinx-Gallery adds an extra cell to the beginning of every generated notebook. This is often for adding code that is required to run properly in the notebook, but not in a .py file. By default, this text is %matplotlib inline  You can choose whatever text you like by modifying the first_notebook_cell configuration parameter. For example, the gallery of this documentation displays a comment along-side each the code shown above. # This cell is added by sphinx-gallery # It can be customized to whatever you like %matplotlib inline  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" "%matplotlib inline") }  If the value of first_notebook_cell is set to None, then no extra first cell will be added to the notebook. ## Using JUnit XML files¶ Sphinx-Gallery can create a JUnit XML file of your example run times, successes, and failures. To create a file named e.g. junit-result.xml in the /build output directory, set the configuration key (path is relative to the HTML output directory): sphinx_gallery_conf = { ... 'junit': '../test-results/sphinx-gallery/junit.xml', }  By default, JUnit XML file generation is disabled (by setting 'junit': ''). JUnit XML files are useful for example on CircleCI builds, where you can add a line like this to get a summary of your example run times in the CircleCI GUI (which will parse the file path doc/_build/test-results/sphinx-gallery/junit.xml and infer the tests came from sphinx-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 related CircleCI doc and blog post. ## Setting log level¶ Sphinx-Gallery logs output at several stages. Warnings can be generated for code that requires case sensitivity (e.g., plt.subplot and plt.Subplot) when building docs on a filesystem that does not support case sensitive naming (e.g., Windows). In this case, by default a logger.warning is emitted, which will lead to a build failure when buidling with -W. The log level can be set with: sphinx_gallery_conf = { ... 'log_level': {'backreference_missing': 'warning'}, }  The only valid key currently is backreference_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 Jupyter notebooks from each gallery into zip files which are made available for download at the bottom of each gallery. To disable this behavior add to the configuration dictionary in your conf.py file: sphinx_gallery_conf = { ... 'download_all_examples': False, }  ## Choosing the thumbnail image¶ For examples that generate multiple figures, the default behavior will use the first figure created in each as the thumbnail image displayed in the gallery. To change the thumbnail image to a figure generated later in an example script, add a comment to the example script to specify the number 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  The default behavior is sphinx_gallery_thumbnail_number = 1. See Choosing the thumbnail figure for an example of this functionality. ## Building without executing examples¶ Sphinx-Gallery can parse all your examples and build the gallery without executing any of the scripts. This is just for speed visualization processes of the gallery and the size it takes your website to display, or any use you can imagine for it. To achieve this you need to pass the no plot option in the build process by modifying your Makefile with: html-noplot:$(SPHINXBUILD) -D plot_gallery=0 -b html $(ALLSPHINXOPTS)$(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in \$(BUILDDIR)/html."


Remember that for Makefile white space is significant and the indentation are tabs and not spaces.

Alternatively, you can add the plot_gallery option to the sphinx_gallery_conf dictionary inside your conf.py to have it as a default:

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


The highest precedence is always given to the -D flag of the sphinx-build command.

## Image scrapers¶

Image scrapers are plugins that allow Sphinx-gallery to detect images produced during 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 both matplotlib and Mayavi images you can do:

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


The default value is 'image_scrapers': ('matplotlib',) which only scrapes matplotlib images.

The following scrapers are supported:

• matplotlib

Sphinx-gallery maintains a scraper for matplotlib figures via the string 'matplotlib'.

• Mayavi

Sphinx-gallery maintains a scraper for Mayavi figures via the string 'mayavi'.

• PyVista

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

• PyGMT

See their website for more information on how to integrate with Sphinx-Gallery.

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

## Resetting modules¶

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

By default, before each example file executes, Sphinx-gallery will reset matplotlib (by using matplotlib.pyplot.rcdefaults()) and seaborn (by trying to unload the module from sys.modules). This is equivalent to the following configuration:

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


Currently, Sphinx-gallery natively supports resetting matplotlib and seaborn. However, you can also add your own custom function to this tuple in order to define resetting behavior for other visualization libraries.

To do so, follow the instructions in Define resetting behavior (e.g., for custom libraries).

## Minimal reported time¶

By default, Sphinx-gallery logs and embeds in the html output the time it took to run each script. If the majority of your examples runs quickly, you may not need this information.

The min_reported_time parameter can be set to a number of seconds. The duration of scripts that ran faster than that amount will not be logged nor embedded in the html output.

## Showing memory consumption¶

Sphinx-Gallery can use memory_profiler, if installed, to report the peak memory during the run of an example. After installing memory_profiler, you can do:

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


## Controlling what output is captured¶

The capture_repr configuration allows the user to control what output is captured, while executing the example .py files, and subsequently incorporated into the built documentation. Data directed to standard output is always captured. The value of the last statement of each code block, if it is an expression, can also be captured. This can be done by providing the name of the ‘representation’ method to be captured in the capture_repr tuple, in order of preference. The representation methods currently supported are:

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

• __str__ - returns a string containing a nicely printable representation of an object. This is what is used when you print() an object or pass it to format().

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

The default setting is:

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


With this setting, for every code block, if the last statement is an expression, Sphinx-Gallery would first attempt to capture the _repr_html_. 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 is always captured.

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

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

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


'Hello world' would be captured for every capture_repr setting as this is directed to standard output. Further,

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

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

• if capture_repr is ('_repr_html_', '__repr__'), the default, Sphinx-Gallery would first attempt to capture _repr_html_. Since this does not exist for a, it will then attempt to capture __repr__. The __repr__ method does exist for a, thus 2 would be also captured in this case.

Matplotlib note: if the 'capture_repr' tuple includes '__repr__' and the last expression is a Matplotlib function call, there will generally be a yellow output box produced in the built documentation, as well as the figure. This is because matplotlib function calls usually return something as well as creating/amending the plot in standard output. For example, matplotlib.plot() returns a list of Line2D objects representing the plotted data. The __repr__ of this list would thus be captured. You can prevent this by:

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

import matplotlib as plt

_ = plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

• add plt.show() (which does not return anything) to the end of your code block. For example:

import matplotlib as plt

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()


The unwanted string output does not occur if 'capture_repr' is an empty tuple, as only data directed to standard output is captured.