Skip to content

Output Preservation and Error Handling

MkDocs-Jupyter provides comprehensive support for preserving notebook outputs and handling errors gracefully during documentation builds.

Output Preservation Features

Supported Output Types

MkDocs-Jupyter preserves all standard Jupyter output types:

  • Text outputs: stdout, stderr, return values
  • Rich outputs: HTML, Markdown, LaTeX, JSON
  • Images: PNG, JPEG, SVG, matplotlib figures
  • DataFrames: Pandas tables with styling
  • Interactive widgets: Static representation
  • Error tracebacks: Formatted error messages

Configuration Options

plugins:
  - mkdocs-jupyter:
      # Core output settings
      execute: true              # Execute notebooks during build
      show_input: true          # Show code cells
      include_source: true      # Add download link

      # Output preservation
      include_requirejs: true    # For interactive outputs
      execute_ignore_cache: false # Use cached outputs
      allow_errors_per_cell: true # Per-cell error handling

      # Error handling
      allow_errors: true        # Continue on errors
      timeout: 100             # Execution timeout (seconds)

Error Handling

Global Error Handling

The allow_errors: true setting allows builds to continue even when notebook cells raise exceptions:

plugins:
  - mkdocs-jupyter:
      allow_errors: true  # Don't fail build on notebook errors

Per-Cell Error Handling

Tag individual cells that are expected to raise errors:

{
  "cell_type": "code",
  "metadata": {
    "tags": ["raises-exception"]
  },
  "source": ["1 / 0  # This will raise ZeroDivisionError"]
}

Error Display

Errors are displayed with formatted tracebacks, making them useful for educational content:

# This will show a nicely formatted error
undefined_variable  # NameError: name 'undefined_variable' is not defined

Cell Visibility Control

Available Tags

Control which parts of cells are visible using tags:

Tag Effect
hide Hide entire cell
hide-cell Hide entire cell (alias)
hide-input Show only output
hide-output Show only code

Tag Configuration

remove_tag_config:
  remove_cell_tags:
    - "hide"
    - "hide-cell"
  remove_all_outputs_tags:
    - "hide-output"
  remove_input_tags:
    - "hide-input"

Using Tags in Jupyter

  1. In Jupyter Lab: View → Show Cell Tags
  2. In Classic Notebook: View → Cell Toolbar → Tags
  3. Add tags: Click on the tag icon and add desired tags

Output Examples

Text Output

Standard print statements and return values are preserved:

print("Hello, World!")
# Output: Hello, World!

42 * 2
# Output: 84

Rich HTML Output

from IPython.display import HTML
display(HTML("<h3>Styled HTML</h3><p style='color: blue;'>Blue text</p>"))

DataFrame Output

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df  # Displays as formatted table

Plot Output

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Sample Plot')
plt.show()  # Plot is saved as image

Best Practices

1. Clear Outputs Before Committing

Keep your repository clean:

jupyter nbconvert --clear-output --inplace notebooks/*.ipynb

2. Use Execution Caching

For faster builds, enable caching:

execute_ignore_cache: false  # Use cached outputs when available

3. Handle Expected Errors

For educational content showing errors:

try:
    risky_operation()
except Exception as e:
    print(f"Error handled: {e}")

4. Control Output Size

For large outputs, consider:

  • Limiting DataFrame display: pd.set_option('display.max_rows', 10)
  • Sampling data: df.sample(100)
  • Using head() or tail() for previews

5. Test Notebook Execution

Before building documentation:

jupyter nbconvert --execute --to notebook --inplace your_notebook.ipynb

Troubleshooting

Build Failures

If builds fail due to notebook errors:

  1. Enable error tolerance: Set allow_errors: true
  2. Skip specific notebooks: Add to execute_ignore list
  3. Increase timeout: For long-running cells
  4. Pre-execute notebooks: Commit with outputs

Missing Outputs

If outputs aren't showing:

  1. Check execution: Ensure execute: true
  2. Verify tags: No hide-output tags
  3. Check logs: Look for execution errors
  4. Test locally: Run notebook in Jupyter first

Performance Issues

For slow builds:

  1. Use caching: execute_ignore_cache: false
  2. Exclude notebooks: Add to execute_ignore
  3. Reduce cell count: Split large notebooks
  4. Optimize code: Profile slow cells

Advanced Features

Conditional Execution

Skip cells based on environment:

import os
if not os.getenv('DOCS_BUILD'):
    # This code only runs in Jupyter, not during docs build
    expensive_operation()

Custom Output Formatting

Create custom output displays:

from IPython.display import display, Markdown

class CustomOutput:
    def _repr_markdown_(self):
        return "**Custom Markdown Output**"

display(CustomOutput())

Progress Indicators

Show progress for long operations:

from tqdm import tqdm
for i in tqdm(range(100)):
    # Process item
    pass

See Examples

These notebooks demonstrate all output preservation and error handling features in action.