sphinxcontrib-jupyter Documentation

This sphinx extension can be used to build a collection of Jupyter notebooks for Sphinx Projects.

Note

It has mainly been written to support the use case of scientific publishing and hasn’t been well tested outside of this domain. Please provide feedback as an issue to this repository.

Requires: Sphinx >= 1.7.2 (for running tests).

One of the main benefits of writing Jupyter notebooks as RST files is to simplify the task of version control for large projects.

Installation

To install the extension:

pip install sphinxcontrib-jupyter

to upgrade your current installation to the latest version:

pip install sphinxcontrib-jupyter --upgrade

Todo

Add installation via conda-forge

Alternative

Another way to get the latest version it is to install directly by getting a copy of the repository:

git clone https://github.com/QuantEcon/sphinxcontrib-jupyter

and then use

python setup.py install

Developers

For developers it can be useful to install using the develop option:

python setup.py develop

this will install the package into the site-wide package directory which is linked to the code in your local copy of the repository. It is not recommended to install this way for common use.

Sphinx Setup

To initially setup a Sphinx project, please refer here.

Note

QuantEcon is currently developing a custom quickstart to assist with setting up a sphinx project customised to use this extension and provide more guidance with the configuration process.

Update the project conf.py file to include the jupyter extension and add the desired configuration settings (see Extension Configuration section for details):

extensions = ["sphinxcontrib.jupyter"]

once the extension is installed you can then run:

make jupyter

The Extension Configuration section includes details on how to configure the extension.

Extension Configuration and Options

The options are split into the different parts of the compilation pipeline that are available in this extension:

Constructing Jupyter Notebooks

jupyter_conversion_mode

Specifies which writer to use when constructing notebooks.

Option Description
“all” (default) compile complete notebooks which include markdown cells and code blocks
“code” compile notebooks that only contain the code blocks.

conf.py usage:

jupyter_conversion_mode = "all"

jupyter_static_file_path

Specify path to _static folder.

conf.py usage:

jupyter_static_file_path = ["source/_static"]

jupyter_header_block

Add a header block to every generated notebook by specifying an RST file

conf.py usage:

jupyter_header_block = ["source/welcome.rst"]

jupyter_default_lang

Specify default language for collection of RST files

conf.py usage:

jupyter_default_lang = "python3"

jupyter_lang_synonyms

Specify any language synonyms.

This will be used when parsing code blocks. For example, python and ipython have slightly different highlighting directives but contain code that can both be executed on the same kernel

conf.py usage:

jupyter_lang_synonyms = ["pycon", "ipython"]

jupyter_kernels

Specify kernel information for the jupyter notebook metadata.

This is used by jupyter to connect the correct language kernel and is required in conf.py.

conf.py usage:

jupyter_kernels = {
    "python3": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python3",
            "name": "python3"
            },
        "file_extension": ".py",
    },
}

Todo

See Issue 196

jupyter_write_metadata

write time and date information at the top of each notebook as notebook metadata

Note

This option is slated to be deprecated

jupyter_options

An dict-type object that is used by dask to control execution

Todo

This option needs to be reviewed

jupyter_drop_solutions

Drop code-blocks that include :class: solution

Values
False (default)
True

Todo

This option needs to be reviewed

jupyter_drop_tests

Drop code-blocks` that include ``:class: test

Values
False (default)
True

Todo

This option needs to be reviewed

jupyter_ignore_no_execute:

Values
False (default)
True

When constructing notebooks this option can be enabled to ignore :class: no-execute for code-blocks. This is useful for html writer for pages that are meant to fail but shouldn’t be included in coverage tests.

conf.py usage:

jupyter_ignore_no_execute = True

jupyter_ignore_skip_test

When constructing notebooks this option can be enabled to ignore :class: skip-test for code-blocks.

Values
False (default)
True

conf.py usage:

jupyter_ignore_skip_test = True

jupyter_allow_html_only

Enable this option to allow .. only:: html pass through to the notebooks.

Values
False (default)
True

conf.py usage:

jupyter_allow_html_only = True

jupyter_target_html

Enable this option to generate notebooks that favour the inclusion of html in notebooks to support more advanced features.

Values
False (default)
True

Supported Features:

  1. html based table support
  2. image inclusion as html figures

conf.py usage:

jupyter_target_html = True

jupyter_images_markdown

Force the inclusion of images as native markdown

Values
False (default)
True

Note

when this option is enabled the :scale: option is not supported in RST.

conf.py usage:

jupyter_images_markdown = True

Executing Notebooks

jupyter_execute_nb

Enables the execution of generated notebooks

Values
False (default)
True

Todo

deprecate this option in favour of jupyter_execute_notebooks

jupyter_execute_notebooks

Enables the execution of generated notebooks

Values
False (default)
True

conf.py usage:

jupyter_execute_notebooks = True

jupyter_dependency_lists

Dependency of notebooks on other notebooks for execution can also be added to the configuration file above in the form of a dictionary. The key/value pairs will contain the names of the notebook files.

conf.py usage:

# add your dependency lists here
jupyter_dependency_lists = {
   'python_advanced_features' : ['python_essentials','python_oop'],
   'discrete_dp' : ['dp_essentials'],
}

jupyter_number_workers

Specify the number cores to use with dask

Values
Integer (default = 1)

conf.py usage:

jupyter_number_workers = 4

jupyter_threads_per_worker

Specify the number of threads per worker for dask

Values
Integer (default = 1)

conf.py usage:

jupyter_threads_per_worker = 1

Converting Notebooks to HTML

jupyter_generate_html

Enable sphinx to generate HTML versions of notebooks

Values
False (default)
True

conf.py usage:

jupyter_generate_html = True

jupyter_html_template

Specify path to nbconvert html template file

Note

Documentation on nbconvert templates can be found here

conf.py usage:

jupyter_html_template = "theme/template/<file>.tpl"

jupyter_make_site

Enable sphinx to construct a complete website

Todo

Document all the extra elements this option does over jupyter_generate_html

This option:

  1. fetches coverage statistics if coverage is enabled.

conf.py usage:

jupyter_make_site = True

jupyter_download_nb

Request Sphinx to generate a collection of download notebooks to support a website

conf.py usage:

jupyter_download_nb = True

jupyter_images_urlpath

Apply a url prefix when writing images in Jupyter notebooks. This is useful when paired with jupyter_download_nb so that download notebooks are complete with web referenced images.

conf.py usage:

jupyter_images_urlpath = "s3://<path>/_static/img/"

Computing Coverage Statistics

jupyter_make_coverage

Enable coverage statistics to be computed

Values
False (default)
True

jupyter_template_coverage_file_path

Provide path to template coverage file

Todo

Document format for template

conf.py usage:

jupyter_template_coverage_file_path = "theme/templates/<file>.json"

It can also be useful to have multiple configurations when working on a large project, such as generating notebooks for working on locally and editing and compiling the project for HTML in a deployment setting. Further details on how to manage large projects can be found here.

An example conf.py is available here

Example conf.py file

After running a sphinx-quickstart you can add the jupyter options needed for your project in a similar fashion to what is shown belows.

# --------------------------------------------
# sphinxcontrib-jupyter Configuration Settings
# --------------------------------------------

# Conversion Mode Settings
# If "all", convert codes and texts into jupyter notebook
# If "code", convert code-blocks only
jupyter_conversion_mode = "all"

# Write notebook creation metadata to the top of the notebook
jupyter_write_metadata = True

# Location for _static folder
jupyter_static_file_path = ["_static"]

# Configure Jupyter Kernels
jupyter_kernels = {
    "python3": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python3",
            "name": "python3"
            },
        "file_extension": ".py",
    },
}

# Configure default language for Jupyter notebooks
# Can be changed in each notebook thanks to the ..highlight:: directive
jupyter_default_lang = "python3"

# Prepend a Welcome Message to Each Notebook
jupyter_welcome_block = "welcome.rst"

# Solutions Configuration
jupyter_drop_solutions = True

# Tests configurations
jupyter_drop_tests = True

# Add Ipython as Synonym for tests
jupyter_lang_synonyms = ["ipython"]

Managing Large Projects

Large projects may require different build pathways due to the time required for execution of embedded code. This can be done by modifying the Makefile to accomodate multiple build pathways.

You may, for example, wish to leave make jupyter simply building notebooks while setting up an alternative make command to target a full website build.

In the Makefile you can add an alternative build target such as:

BUILDWEBSITE  = _build/website

and then you can modify options (set in the conf.py file) using the -D flag.

website:
    @$(SPHINXBUILD) -M jupyter "$(SOURCEDIR)" "$(BUILDWEBSITE)" $(SPHINXOPTS) $(O) -D jupyter_make_site=1 -D jupyter_generate_html=1 -D jupyter_download_nb=1 -D jupyter_execute_notebooks=1 -D jupyter_target_html=1 -D jupyter_images_markdown=0 -D jupyter_html_template="theme/templates/lectures-nbconvert.tpl" -D jupyter_download_nb_urlpath="https://lectures.quantecon.org/"

this will setup a new folder _build/website for the new build pathway to store resultant files from the options selected.

Note

this method also preserves the sphinx cache mechanism for each build pathway.

Warning

Issue #199 will alter this approach to include all configuration settings in the conf.py file and then the different pipelines can be switched off in the Makefile which will be less error prone.

Credits

This project is supported by QuantEcon

Many thanks to the lead developers of this project.

Contributors

Projects using Extension

  1. QuantEcon Lectures

If you find this extension useful please let us know at contact@quantecon.org

LICENSE

Copyright © 2019 QuantEcon Development Team: BSD-3 All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Indices and tables