Skip to main content

nbmake

codecov codecov PyPI versions PyPI versions PyPI Downloads

What? Pytest plugin for testing and releasing notebook documentation

Why? To raise the quality of scientific material through better automation

Who is this for? Research/Machine Learning Software Engineers who maintain packages/teaching materials with documentation written in notebooks.

Functionality

  1. Executes notebooks using pytest and nbclient, allowing parallel notebook testing
  2. Optionally writes back to the repo, allowing faster building of nbsphinx or jupyter book docs

Quick Start

If you have a notebook that runs interactively using an ipython kernel, you can try testing it automatically as follows:

pip install pytest nbmake
pytest --nbmake **/*ipynb

Configure Cell Timeouts

You can configure the cell timeout with the following pytest flag:

pytest --nbmake --nbmake-timeout=3000 # allows each cell 3000 seconds to finish

Allow Errors For a Whole Notebook

This configuration must be placed in the notebook's top-level metadata (not cell-level metadata).

Your notebook should look like this:

{
  "cells": [ ... ],
  "metadata": {
    "kernelspec": { ... },
    "execution": {
      "allow_errors": true,
      "timeout": 300
    }
  }
}

Allow a Cell to Throw an Exception

A cell with the following metadata can throw an exception without failing the test:

  "metadata": {
    "tags": [
      "raises-exception"
    ]
  }

Ignore a Code Cell

A cell with the following metadata will not be executed by nbmake

{
  "language": "python",
  "custom": {
    "metadata": {
      "tags": [
        "skip-execution"
      ]
    }
  }
}

Override Notebook Kernels when Testing

Regardless of the kernel configured in the notebook JSON, you can force nbmake to use a specific kernel when testing:

pytest --nbmake --nbmake-kernel=mycustomkernel

Add Missing Jupyter Kernel to Your CI Environment

If you are not using the flag above and are using a kernel name other than the default ‘python3’, you will see an error message when executing your notebooks in a fresh CI environment: Error - No such kernel: 'mycustomkernel'

Use ipykernel to install the custom kernel:

python -m ipykernel install --user --name mycustomkernel

If you are using another language such as c++ in your notebooks, you may have a different process for installing your kernel.

Parallelisation

For repos containing a large number of notebooks that run slowly, you can run each notebook in parallel using pytest-xdist.

pip install pytest-xdist

pytest --nbmake -n=auto

It is also possible to parallelise at a CI-level using strategies, see example

Build Jupyter Books Faster

Using xdist and the --overwrite flag let you build a large jupyter book repo faster:

pytest --nbmake --overwrite -n=auto examples
jb build examples

Find missing imports in a directory of failing notebooks

It's not always feasible to get notebooks running from top to bottom from the start.

You can however, use nbmake to check that there are no ModuleNotFoundErrors:

pytest \
  --nbmake \
  --nbmake-find-import-errors \ # Ignore all errors except ModuleNotFoundError
  --nbmake-timeout=20 # Skip past cells longer than 20s

Mock out variables to simplify testing

If your notebook runs a training process that takes a long time to run, you can use nbmake's mocking feature to overwrite variables after a cell runs:

{
  "cells": [
    ...,
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "nbmake": {
          "mock": {
            // these keys will override global variables after this cell runs
            "epochs": 2,
            "config": "/test/config.json",
            "args": {
              "env": "test"
            }
          }
        }
      },
      "outputs": [],
      "source": [
        "epochs = 10\n",
        "..."
      ]
    },
    ...
  ],
  ...
}

Run test logic after a cell executes

You can fetch CI secrets and run assertions after any cell by putting scripts in the cell metadata under nbmake.post_cell_execute:

{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbmake": {
     "post_cell_execute": [
       "y = 3",
       "z = x+y"
     ]
    }
   },
   "outputs": [],
   "source": [
    "x = 1\n",
    "y = 2\n",
    "z = 0\n",
    "# this cell has a post_cell_execute that assigns y and z"
   ]
  },

Advice on Usage

nbmake is best used in a scenario where you use the ipynb files only for development. Consumption of notebooks is primarily done via a docs site, built through jupyter book, nbsphinx, or some other means. If using one of these tools, you are able to write assertion code in cells which will be hidden from readers.

Pre-commit

Treating notebooks like source files lets you keep your repo minimal. Some tools, such as plotly may drop several megabytes of javascript in your output cells, as a result, stripping out notebooks on pre-commit is advisable:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/kynan/nbstripout
    rev: master
    hooks:
      - id: nbstripout

See https://pre-commit.com/ for more...

Disable Nbmake

Implicitly:

pytest

Explicitly:

pytest -p no:nbmake

See Also:

Release files for nbmake 1.5.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nbmake 1.5.5
File Size Uploaded
nbmake-1.5.5.tar.gz 85.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for nbmake 1.5.5
File Interpreter ABI Platform
nbmake-1.5.5-py3-none-any.whl Python 3 none any Details

Total release size: 98.7 kB

Release files / nbmake-1.5.5.tar.gz

Download URL nbmake-1.5.5.tar.gz
Size 85.9 kB
Tags Source
SHA-256 checksum
How to use checksums
239dc868ea13a7c049746e2aba2c229bd0f6cdbc6bfa1d22f4c88638aa4c5f5c
BLAKE2b-256 checksum
How to use checksums
439aaae201cee5639e1d562b3843af8fd9f8d018bb323e776a2b973bdd5fc64b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.5.11

Release files / nbmake-1.5.5-py3-none-any.whl

Download URL nbmake-1.5.5-py3-none-any.whl
Size 12.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c6fbe6e48b60cacac14af40b38bf338a3b88f47f085c54ac5b8639ff0babaf4b
BLAKE2b-256 checksum
How to use checksums
ebbeb257e12f9710819fde40adc972578bee6b72c5992da1bc8369bef2597756
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.5.11

Release history Release notifications | RSS feed

This release

1.5.5 This release

2 release files

1.5.4

2 release files

1.5.3

2 release files

1.5.2

2 release files

1.5.1

2 release files

1.5.0

2 release files

1.4.6

2 release files

1.4.5

2 release files

1.4.3

2 release files

1.4.1

2 release files

1.4

2 release files

1.3.5

2 release files

1.3.4

2 release files

1.3.3

2 release files

1.3.2

2 release files

1.3.1

2 release files

1.3.0

2 release files

1.2.1

2 release files

1.2

2 release files

1.1

2 release files

1.0

2 release files

0.10

2 release files

0.9

2 release files

0.8

2 release files

0.7

2 release files

0.6

2 release files

0.5

2 release files

0.4

2 release files

0.3

2 release files

0.2

2 release files

0.1

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page