nbdime (Jupyter Notebook Diff & Merge)

4.0.4 · active · verified Thu Apr 16

nbdime provides tools for diffing and merging Jupyter Notebooks. It offers both a command-line interface for integration with version control systems (like Git) and a visual, interactive web interface for richer diffs and merges. The library is currently at version 4.0.4 and is actively maintained by the Project Jupyter team, with releases often coinciding with major JupyterLab updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create two simple Jupyter notebooks and then use the `nbdime` command-line tool to perform a diff between them, showing the output directly in the terminal. The default `nbdime diff` command would open a browser for a richer visual diff.

import nbformat
from pathlib import Path
import subprocess

# Create two dummy notebooks for demonstration
nb1 = nbformat.v4.new_notebook()
nb1.cells.append(nbformat.v4.new_code_cell("print('Hello from A')"))
nb1_path = Path("notebook_a.ipynb")
with open(nb1_path, "w", encoding="utf-8") as f:
    nbformat.write(nb1, f)

nb2 = nbformat.v4.new_notebook()
nb2.cells.append(nbformat.v4.new_code_cell("print('Hello from B')"))
nb2.cells.append(nbformat.v4.new_markdown_cell("## A new section\nThis is a new section in notebook B."))
nb2_path = Path("notebook_b.ipynb")
with open(nb2_path, "w", encoding="utf-8") as f:
    nbformat.write(nb2, f)

print(f"Created {nb1_path} and {nb2_path}")

# Run nbdime diff from the command line
print("\n--- Running nbdime diff in terminal mode ---")
try:
    # Use --diff-alg=terminal to get output directly in the console
    result = subprocess.run(
        ["nbdime", "diff", str(nb1_path), str(nb2_path), "--diff-alg=terminal"],
        capture_output=True, text=True, check=True
    )
    print(result.stdout)
except subprocess.CalledProcessError as e:
    print(f"Error running nbdime diff: {e.stderr}")

# To open in a browser (default behavior if --diff-alg is not specified)
# print("\n--- Running nbdime diff in browser (opens new tab) ---")
# subprocess.Popen(["nbdime", "diff", str(nb1_path), str(nb2_path)])
# print("Check your browser for the visual diff. Press Ctrl+C to stop this script after viewing.")
# import time; time.sleep(10) # Give time to view, then uncomment cleanup

# Clean up
nb1_path.unlink()
nb2_path.unlink()
print(f"\nCleaned up {nb1_path} and {nb2_path}")

view raw JSON →