Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import io
import os
import re
import nbformat
import nbstripout
def post_save_hook(model, os_path, contents_manager, **kwargs):
Custom hook to strip outputs, unnecessary metadata and trailing spaces
from jupyter notebooks to be stored in git.
base, _ = os.path.splitext(os_path)
# Only process notebooks
if model["type"] != "notebook":
# Only process notebooks in the RBniCS repository
if not re.compile(r"RBniCS").search(base):
# Do not bother running if the notebook name ends with `Untitled[0-9]*`
if re.compile(r"Untitled[0-9]*$").search(base):
# Read in notebook content
with, "r", encoding="utf8") as f:
nb =, as_version=nbformat.NO_CONVERT)
# Strip outputs and unnecessary keys
extrakeys = ["metadata.celltoolbar", "metadata.kernel_spec.display_name", "",
"metadata.language_info.codemirror_mode.version", "metadata.language_info.pygments_lexer",
"metadata.language_info.version", "metadata.toc", "metadata.notify_time", "metadata.varInspector",
"cell.metadata.heading_collapsed", "cell.metadata.hidden", "cell.metadata.code_folding",
"cell.metadata.tags", "cell.metadata.init_cell"]
nbstripout.strip_output(nb, keep_output=False, keep_count=False, extra_keys=" ".join(extrakeys))
# Strip trailing whitespaces
for cell in nb.cells:
if cell["cell_type"] == "code":
cell["source"] = "\n".join([line.rstrip() for line in cell["source"].split("\n")])
# Overwrite notebook content
with, "w", encoding="utf8") as f:
nbformat.write(nb, f)
c.FileContentsManager.post_save_hook = post_save_hook

This comment has been minimized.

Copy link
Owner Author

@francesco-ballarin francesco-ballarin commented Aug 22, 2020

RBniCS jupyter tutorials configuration for git integration

Save the file in a jupyter config path (for instance $HOME/.jupyter; further available config paths can be obtained from jupyter --paths). This file provides a custom hook to strip output from jupyter notebooks to be stored in git.

Afterwards, go to your RBniCS clone and run nbdime config-git --enable. This allows to configure custom diff and merge commands for *.ipynb files.

Dependencies: nbstripout and nbdime.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment