Interactive content: Run Python inside your book#

User types

This section is useful for user type 5.

Sphinx Extension

Our book has been enable to run Python code live in the browser (thanks Max!). This extension makes code cells in your .ipynb book pages editable and executable by the reader! Opposed to the original sphinx-thebe extensions, our extension runs python in the reader’s browser and doesn’t rely on an external webserver for the python kernel. We highly recommend this extension as it allows you to use the strength of combining text/figures and code of a jupyter book with interactivity!

This page contains some installation instructions and the other sections show how to use this functionality to create interactive figures and feedback on code

To see this happening, click –> Live Code on the top right corner of this page

print('hello world')

Note

There are two tools presented on this page: Sphinx-Thebe and JupyterLite (at the bottom). Both tools rely on Pyodide, a software tool that is the backbone allowing for a Jupyter Notebook-like experience in a web browser without requiring the user to install any software.

Most of the TeachBooks Team uses a custom version of Sphinx-Thebe, a Sphinx Extension, because it can be integrated directly in a TeachBooks and provides a notebook-style experience (a “your page is a notebook” experience), whereas JupyterLite is more of a “notebook-in-a-window-in-your-page” experience.

This use of Sphinx-Thebe with Pyodide was made possible in Summer 2023 by Max Guichard, originally as a set of static files loaded in the MUDE Book. In January of 2024 this was converted to a custom Sphinx extension hosted on MUDE’s TU Delft GitLab. As of February, 2025, we are currently working on improving this extension and providing it via PyPI, similar to our other tools. Stay tuned!

Sphinx-Thebe can be configured to use two types of “computers” in the background: Pyodide (what we use, running 100% in the browser) and Binder, which is a third-party service that provides cloud-based computers for free (i.e., code runs on a separate server). This is a great tool, but often the time required to wait for the free cloud computer to be ready is too long (or simply does not work). As most of our teaching applications only require simple pieces of code, we prefer the Pyodide-based options because it is more reliable and loads faster.

Setting up Python live coding#

To set up the Python live coding you need to add our own sphinx-thebe extension to your book. This extensions doesn’t rely on a 3rd party like Binder and it supports local python execution and custom features. Therefore, you need to add some lines to requirements.txt and _config.yml

For requirements.txt add the following lines:

--extra-index-url https://gitlab.tudelft.nl/api/v4/projects/11239/packages/pypi/simple
sphinx-thebe ~= 0.9.9

This will download the correct version of the sphinx extension when the book is built on the server (which loads the required packages from requirements.txt)

If you want to build the book locally, you need to install this version of sphinx-thebe in your environment as well with:

pip install -r requirements.txt

Afterwards, this sphinx extension needs to be enabled in your book. This can be done by adding the following lines to _config.yml:

launch_buttons:
  thebe: true

sphinx:
  config:
    html_js_files:
    - https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js
    thebe_config:
      use_thebe_lite: true
      exclude_patterns: ["**/_*.yml", "**/*.md", "**/*.ipynb"]

The html_js_files link calls for some required javascript files. use_thebe_lite makes sure you initiate our adapted sphinx thebe extensions. The exclude_patterns makes sure you import all files so that they can be accessed from your code, except for the files matching the patterns shown.

Note

If you’ve a lot of big files which are not used by the code, the build book repository might grow a lot in size. Include unnecessary filetypes like images (i.e. "**/*.png) to exclude_patterns. Make sure you use proper markdown or MyST syntax for referencing to images. Using HTML code might lead to figures not being available in the final book.

By launch_buttons you initiate the –> Live Code on the top right corner of every page generated from a .ipynb file.

Note, if you’re messing around with html_theme_options (for example when adding more buttons), all button behaviour is affected. In that case, as opposed to the jupyter book documentation, all buttons have to be specified from within sphinx: html_theme_options where you might also specify other buttons as well (ie. the code repository button).

sphinx:
  config:
    html_js_files:
    - https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js
    thebe_config:
      use_thebe_lite: true
      exclude_patterns: ["**/_*.yml", "**/*.md", "**/*.ipynb"]
    html_theme_options:
      repository_url: "hello!"
      use_repository_button: true
      launch_buttons:
        thebe: true

Instructions: local build#

To test the fuctionality, you have to run a local server, otherwise the interactivity doens’t work. So, you cannot just open the index.html file any more. This can be done with the steps shown in Local Server to view interactive elements locally.

If you push to main, you can test the interactivity on the book-draft website as well.

Custom cell tags#

With the extended functionality of live code, additional cell tags have been developed to be added to python cells (not markdown cells) in any .ipynb file, next to the [existing tags] of the jupyter book (https://jupyterbook.org/en/stable/content/metadata.html):

  • disable-execution-cell disables the ability to execute the cell when thebe is activated. This might be useful if you notebook file includes interactivity for only a part of the coding cells

  • disable-execution-page disables the ability to execute the entire page. This might be useful if you use python code for creating a page, but the code is not part of the actual content of the book.

  • auto-execute-page automatically starts the thebe live coding functionality whenever the page is opened. This is particularly useful if you’re using widgets on a page.

  • thebe-init directly starts running this cell as soon as the thebe live coding functionality starts.

  • thebe-remove-input-init, as thebe-init, starts the cell directly as soon as the thebe live coding functionality starts. However, the input is not shown to the students (in static and interactive mode). The original remove-input tag will not work as it deletes the entire cell, so it can never be executed.

Additional packages#

The python kernel doesn’t have all packages standard included. Some of the most used packages which are included are:

  • python

  • numpy

  • scipy

  • sympy

  • matplotlib

  • ipywidgets

If you’d like to install more package, you can do so by added a codecell (preferably hidden using thebe-remove-input-init) with the following command:

import micropip
await micropip.install("package_name")

This will install the packages: Micropip will look at the Pyodide package index, but also at the general PyPi index. If a package is pure python (i.e. no C extensions), then it can also be used by Pyodide.

Custom packages#

If you have some custom packages you can also create a wheel to import. Therefore, create a wheel from your package by running this in the root directoy of your package:

python setup.py bdist_wheel

Copy the wheel from dist/<something>.whl to your book and import the package from within a notebook using:

import micropip
await micropip.install('<directory>/<something>.whl')

Preferably with the tag thebe-remove-input-init.

Other packages not in Pyodide but on PyPI#

If the packages are not included in Pyodide, you can use `pip:

%pip install package_name

Import module from subdirectory#

In case you’ve a module in a subdirectory you cannot do directly import <module_name> as <local_module_name>. To solve this, you first have to add that subdirectory to the path with sys.path.insert(1, '/<module_name/subdirectory>') (preferably in a hidden cell with theme-remove-input-init)

Alternative with JupyterLite (less well integrated)#

Another option to use python in your browser is to use JupyterLite. However, compared to Sphinx-Thebe, described above, this doesn’t give a similar seamless interface within your page. Nevertheless, depending on your application, JupyterLite could be a useful tool, especially as it allows for three IDE types: Jupyter Notebook, Jupyter Lab and the iPython REPL.

One example use case is to create ‘iframe-like’ Ipython consoles / jupyterbook / jupyter lab environments in your book. As these ‘iframes’ are separate modules added to your page, the integration with the other content in your book is less flexible as with our sphinx-thebe extension. If you need to manage several different environments for JupyterLite within the book, you can use a JupyterLite session from a separate repo with the jupyter lab interface anyway, so you get the full browser experience. Alternatively, the ipython REPL better can be useful, as shown in our Python for Engineers book.

Tip

The TeachBooks Team has focused primarily on the use of Sphinx-Thebe and has not looked at JupyterLite over the last couple years. If you have an interesting application of this tool for teaching, please get in touch, we would love to see it! You can use GitHub Discussions or sent us an email at info@teachbooks.io.